水题不解释,用一个参数保存部分和,当到达叶节点时,判断是否跟给定的相等。注意树中节点的数值可正可负,所以不能用和来剪枝。还有就是只要存在即可,因此用左右字数的或来代表最后的结果。
bool hasPath(TreeNode *root, int sum, int tpsum){
if(root == NULL) return false;
tpsum += root->val;
if(!root->left&&!root->right){
if(tpsum == sum)
return true;
return false;
}
bool res = false;
if(root->left)
res |= hasPath(root->left, sum, tpsum);
if(root->right)
res |= hasPath(root->right, sum, tpsum);
return res;
}
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
return hasPath(root, sum, 0);
}
};