Path Sum Problem


Description

LeetCode Problem 112.

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

Example 1:

1
2
3
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.

Example 2:

1
2
3
4
5
6
Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.

Example 3:

1
2
3
Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    bool checkPathSum(TreeNode* root, int sum, int accu) {
        if ((root->left == NULL) && (root->right == NULL)) {
            if (accu + root->val == sum)
                return true;
            else
                return false;
        } else if (root->left == NULL) {
            return checkPathSum(root->right, sum, accu+root->val);
        } else if (root->right == NULL) {
            return checkPathSum(root->left, sum, accu+root->val);
        } else {
            return ((checkPathSum(root->left, sum, accu+root->val) || (checkPathSum(root->right, sum, accu+root->val))));
        }
        
    }
    bool hasPathSum(TreeNode* root, int sum) {
        if (root == NULL)
            return false;
        return checkPathSum(root, sum, 0);
    }
};




Related Posts

Sum Root To Leaf Numbers Problem

LeetCode 129. You are given the root of a binary...

Populating Next Right Pointers In Each Node Problem

LeetCode 116. You are given a perfect binary tree where...

Populating Next Right Pointers In Each Node II Problem

LeetCode 117. Given a binary tree, populate each next pointer...

Path Sum Problem

LeetCode 112. Given the root of a binary tree and...

Minimum Depth Of Binary Tree Problem

LeetCode 111. Given a binary tree, find its minimum depth....

Balanced Binary Tree Problem

LeetCode 110. Given a binary tree, determine if it is...