链接: https://oj.leetcode.com/problems/path-sum/
深度优先搜索,.求出个从根到叶子节点的和..注意树中有负树
/**
* 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 dfs(TreeNode *Node,int pathsum,int sum)
{
if(Node!=NULL)
{
if(Node->left)
if(dfs(Node->left,pathsum+Node->left->val,sum))
return true;
if(Node->right)
if(dfs(Node->right,pathsum+Node->right->val,sum))
return true;
}
if(pathsum==sum&&Node->right==NULL&&Node->left==NULL)
return true;
return false;
}
bool hasPathSum(TreeNode *root,int sum )
{
if(root==NULL)
return false;
return dfs(root,0,sum-root->val);
}
};