0112. Path Sum¶
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:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Example 2:
Input: root = [1,2,3], targetSum = 5
Output: false
Example 3:
Input: root = [1,2], targetSum = 0
Output: false
Constraints:
- The number of nodes in the tree is in the range
[0, 5000]
. -1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
Analysis¶
The path has be from root to leaf, and we need to make sure our code satisfy both:
- if
node->left==nullptr && node->right==nullptr
, then the node is a leaf node - if
current sum==sum
, then current path sum is satisfied.
We can then use recursion to solve.
- TIme: O(n) where n is number of nodes in the tree
- Space: O(n) worst case when tree is a linkedlist
Code¶
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root) return false;// already visited to the children node of leaf
sum -= root -> val;
// is leaf node + curr sum == target sum
if (!sum && !root -> left && !root -> right) return true;
return hasPathSum(root -> left, sum) || hasPathSum(root -> right, sum);
}
};
Last update:
April 1, 2022