-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRootLeafPathFinder.java
42 lines (35 loc) · 1.03 KB
/
RootLeafPathFinder.java
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package org.sean.recursive;
import org.sean.tree.TreeNode;
/***
* 112. Path Sum
*/
public class RootLeafPathFinder {
private TreeNode top;
private boolean findPathSum(TreeNode node, int sum, int curr) {
int value = curr + node.val;
if(node.left == null && node.right == null) {
return (value == sum);
}else {
boolean leftFound = false;
if(node.left != null) {
leftFound = findPathSum(node.left, sum, value);
}
boolean rightFound = false;
if(node.right != null) {
rightFound = findPathSum(node.right, sum, value);
}
return leftFound || rightFound;
}
}
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null)
return false;
int s = root.val;
if(root.left == null && root.right == null) {
return s == sum;
}else {
top = root;
return findPathSum(root, sum, 0);
}
}
}