/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool recursive(TreeNode *cur,int sum,int tmpSum)
{
if(cur->left==NULL&&cur->right==NULL)//叶子节点
{
if(tmpSum==sum)
return true;
else
return false;
}
bool lefCheck=false,rigCheck=false;
if(cur->left!=NULL)
lefCheck=recursive(cur->left,sum,tmpSum+(cur->left->val));
if(cur->right!=NULL)
rigCheck=recursive(cur->right,sum,tmpSum+(cur->right->val));
return lefCheck||rigCheck;
}
bool hasPathSum(TreeNode *root, int sum) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root==NULL)
return false;
return recursive(root,sum,root->val);
}
};
【leetcode】Path Sum
最新推荐文章于 2020-01-02 15:30:00 发布