-
-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathPathSum.java
More file actions
43 lines (30 loc) · 896 Bytes
/
Copy pathPathSum.java
File metadata and controls
43 lines (30 loc) · 896 Bytes
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
43
package leetcode.easy;
import util.TreeNode;
import java.util.Stack;
public class PathSum {
boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
// Create 2 stacks for the path and the sums
Stack<TreeNode> path = new Stack<>();
Stack<Integer> sumPath = new Stack<>();
path.push(root);
sumPath.push(root.val);
while (!path.isEmpty()) {
TreeNode temp = path.pop();
int tempVal = sumPath.pop();
// If a child node and we find the sum total, return true
if (temp.left == null && temp.right == null && tempVal == sum)
return true;
if (temp.right != null) {
path.push(temp.right);
sumPath.push(temp.right.val + tempVal);
}
if (temp.left != null) {
path.push(temp.left);
sumPath.push(temp.left.val + tempVal);
}
}
return false;
}
}