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.
For example:Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1return true, as there exist a root-to-leaf path
5->4->11->2
which sum is 22.
题目的意思是说有没有一条从根结点到叶子结点的路径,使得路径上的数之和等于给定的数sum。
思路:
若当前结点为NULL,则返回false;
若当前结点不为NULL,进行如下判断:
当不是叶子结点的时候,应该递归为左结点+右节点,并且传递的参数sum需要减去val;
当为叶子结点的时候,需要进行如下判断:
当前值val是否和传递过来的sum是否相等?如果相等,则说明从根结点到该叶子结点路径上的所有val之和为sum,返回true;否则这条路径上的之和不为sum,返回false。
**
* 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==NULL){
return false;
}
else{
if(root->left==NULL && root->right==NULL){
if(sum==root->val)
return true;
else
return false;
}
else{
bool flag1=false,flag2=false;
if(root->left!=NULL)
flag1 = hasPathSum(root->left,sum - root->val) ;
if(root->right!=NULL)
flag2 = hasPathSum(root->right,sum - root->val);
return flag1+flag2;
}
}
}
};