-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum.java
More file actions
62 lines (57 loc) · 2.06 KB
/
Copy pathPathSum.java
File metadata and controls
62 lines (57 loc) · 2.06 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
return hasPathSum1(root.left, sum, root.val) || hasPathSum1(root.right, sum, root.val);
return hasPathSum2(root, sum);
return hasPathSum2_recursive(root, sum);
}
private boolean hasPathSum2_recursive(TreeNode root, int sum) {
if (root == null) return false;
if (root.left == null && root.right == null) {
if (root.val == sum) return true;
}
if (root.left != null) {
root.left.val += root.val;
}
if (root.right != null) {
root.right.val += root.val;
}
return hasPathSum2_recursive(root.left, sum) || hasPathSum2_recursive(root.right, sum);
}
private boolean hasPathSum2(TreeNode root, int sum) {
if (root == null) return false;
if (root.left == null && root.right == null) return root.val == sum;
Deque<TreeNode> ts = new ArrayDeque<>();
ts.push(root);
while (!ts.isEmpty()) {
TreeNode walker = ts.pop();
if (walker.left == null && walker.right == null) {
if (walker.val == sum) return true;
}
if (walker.left != null) {
walker.left.val += walker.val;
ts.push(walker.left);
}
if (walker.right != null) {
walker.right.val += walker.val;
ts.push(walker.right);
}
}
return false;
}
// f(root) = f(root.left) || f(root.right)
// f(nodeLeaf) && s == sum return true
private boolean hasPathSum1(TreeNode root, int sum, int ps) {
if (root == null) return false;
if (root.left == null && root.right == null) return root.val + ps == sum;
return hasPathSum1(root.left, sum, root.val+ps) || hasPathSum1(root.right, sum, root.val+ps);
}
}