1.题目
判断是否从根到叶子的路径和跟给定sum相同的
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.
2.算法
用递归法,看看左子树或右子树有没有满足条件的路径
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null)
return false;
if(root.left == null && root.right==null && root.val==sum)
return true;
return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
}