LeetCode: Path Sum

LeetCode: Path Sum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

/**
* Created by hzhou on 4/22/15. [email protected]
*/
public class PathSum {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
return helper(root, sum);
}
private boolean helper(TreeNode root, int sum) {
if (root != null && root.left == null && root.right == null) {
return sum == root.val;
}
boolean left = false;
boolean right = false;
assert root != null;
if (root.left != null) {
left = helper(root.left, sum - root.val);
}
if (root.right != null) {
right = helper(root.right, sum - root.val);
}
return left || right;
}
}