-
Notifications
You must be signed in to change notification settings - Fork 4
/
Solution.java
59 lines (52 loc) · 1.29 KB
/
Solution.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
package _653;
import java.util.Stack;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
int num;
TreeNode next;
stack.push(root);
while (!stack.empty()) {
TreeNode node = stack.pop();
next = root;
num = k - node.val;
while (next != null) {
if (next.val == num) {
if (next == node) {
break;
} else {
return true;
}
} else if (num > next.val) {
next = next.right;
} else {
next = next.left;
}
}
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
return false;
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}