在遍历树的同时计算是否到达叶子节点,如果到达叶子节点时,pathsum还不等于sum则跳出。
/**
* 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) return false;
bool left = false;
bool right = false;
if(!root->left&&!root->right){
if(sum == root->val)
return true;
else
return false;
}
int newsum = sum - root->val;
if(root->left) left = hasPathSum(root->left,newsum);
if(root->right) right = hasPathSum(root->right,newsum);
return left || right;
}
};