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

Vertical Order Traversal Of A Binary Tree Problem

LeetCode 987. Given the root of a binary tree, calculate...

Univalued Binary Tree Problem

LeetCode 965. A binary tree is uni-valued if every node...

Sum Of Distances In Tree Problem

LeetCode 834. There is an undirected connected tree with n...

Smallest Subtree With All The Deepest Nodes Problem

LeetCode 865. Given the root of a binary tree, the...

Smallest String Starting From Leaf Problem

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

Similar String Groups Problem

LeetCode 839. Two strings Xand Yare similar if we can...