给定一个二叉树和一个值\ sum sum,判断是否有从根节点到叶子节点的节点值之和等于\ sum sum 的路径,
例如:
给出如下的二叉树,\ sum=22 sum=22,
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool hasPathSum(TreeNode* root, int sum) {
if(!root) return false;
// write code here
return dfs(root,sum);
}
bool dfs(TreeNode * root,int parentSum) {
if(parentSum==0 && !root) return true;
if(!root) return false;
int cur = parentSum - root -> val;
if (cur==0 && (!root ->left) &&(!root ->right)) return true;
bool left=false,right=false;
if(root -> left) left = dfs(root ->left, cur);
if(left) return true;
if(root -> right) right = dfs(root ->right,cur);
return right;
}
};