题目
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.
答案
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
return recur(root, sum, 0);
}
private boolean recur(TreeNode root, int sum, int mysum) {
if(root.left == null && root.right == null) {
return sum == mysum + root.val;
}
boolean l = false, r = false;
if(root.left != null)
l = recur(root.left, sum, mysum + root.val);
if(root.right != null)
r = recur(root.right, sum, mysum + root.val);
return l || r;
}
}