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.
Example:
Given the below binary tree and sum = 22,
C++
lic:
bool hasPathSum(TreeNode* root, int sum) {
if(root == nullptr)
return false;
return DFS(root,0,sum);
}
bool DFS(TreeNode* root,int num,int sum)
{
if(root == nullptr&&num == sum)
return true;
if(root == nullptr&&num != sum)
return false;
num = num + root->val;
if(!root->left)
return DFS(root->right,num,sum);
if(!root->right)
return DFS(root->left,num,sum);
return DFS(root->left,num,sum)||DFS(root->right,num,sum);
}