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.
For example:
Given the below binary tree andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.
这道题可以用pre-order对于二叉树自上到下来递归,每次递归生成一个减掉root.val的新sum,然后先判断sum是否为零并且当前的root是否为leaf,若满足则return true,否则对其左儿子和右儿子分别递归,返回左儿子结果||右儿子结果,如此往复直到root是null(本身是leaf,此时返回false)。
class Solution{
public boolean hasPathSum(TreeNode root, int sum){
// base case
if(root == null){
return false;
}
int newSum = sum - root.val;
if (newSum == 0 && root.left == null && root.right == null){
return true;
}
boolean left = hasPathSum(root.left, newSum);
boolean right = hasPathSum(root.right, newSum);
return left || right;
}
}