- Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Runtime: 16 ms, faster than 20.27% of C online submissions for Path Sum.
Memory Usage: 19.2 MB, less than 17.86% of C online submissions for Path Sum.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool helper(struct TreeNode* root, int sum,int calc){
if(root==NULL)
return 0;
calc+=root->val;
if(root->left==NULL && root->right==NULL)
if(calc==sum)
return 1;
return helper(root->left,sum,calc) || helper(root->right,sum,calc);
}
bool hasPathSum(struct TreeNode* root, int sum) {
int calc = 0;
return helper(root,sum,calc);
}
网友评论