-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy path112.java
67 lines (59 loc) · 1.9 KB
/
112.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
__________________________________________________________________________________________________
sample 0 ms submission
/**
* 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) {
if(root==null)return false;
int s = sum-root.val;
boolean ans = false;
if(root.left==null && root.right==null && s==0)return true;
ans = ans || hasPathSum(root.left,s);
ans = ans || hasPathSum(root.right,s);
return ans;
}
}
__________________________________________________________________________________________________
sample 35144 kb submission
/**
* 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) {
if (root == null) return false;
Stack<TreeNode> treeStack = new Stack<>();
Stack<Integer> sumStack = new Stack<>();
treeStack.push(root);
sumStack.push(sum-root.val);
while (!treeStack.isEmpty()) {
TreeNode n = treeStack.pop();
Integer curr = sumStack.pop();
if (n.left == null && n.right == null && curr == 0) {
return true;
}
if (n.right != null) {
treeStack.push(n.right);
sumStack.push(curr-n.right.val);
}
if (n.left != null) {
treeStack.push(n.left);
sumStack.push(curr-n.left.val);
}
}
return false;
}
}
__________________________________________________________________________________________________