题目描述
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
样例
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
思路
本题是考察遍历的一种方式,要注意的点包括:
1、没说不能是负数
2、空树的时候应当返回的值
3、同时满足和为sum和root-to-leaf path的条件,要注意root-to-leaf path的判定
因为一定要遍历到叶子节点,所以写清楚叶子节点的递归终止情况就行了。
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root==NULL)
{
return false;
}
if(root->left==NULL&&root->right==NULL)
{
if(sum==root->val)
return true;
return false;
}
return hasPathSum(root->left,sum-root->val)
||hasPathSum(root->right,sum-root->val);
}
};
感觉糟糕的时候需要再来一瓶。