Q112. Path Sum
Last updated
Last updated
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(!root) return false;
bool res = false;
treePath(root, root->val, sum, res);
return res;
}
private:
void treePath(TreeNode* root, int path, int sum, bool& res){
if(!root->left && !root->right){
res = res || (path == sum);
return;
}
if(root->left) treePath(root->left, path+root->left->val, sum, res);
if(root->right) treePath(root->right, path+root->right->val, sum, res);
}
};