-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathNew_Question.java
64 lines (31 loc) · 1.07 KB
/
New_Question.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
Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input: root = [5,3,6,2,4,null,7], k = 9
Output: true
Solution:
if(root==null){
return false;
}
Queue<TreeNode>q = new LinkedList<>();
HashSet<Integer>ss = new HashSet<>();
q.offer(root);
while(!q.isEmpty()){
int sz = q.size();
while(sz-->0){
TreeNode n = q.poll();
int nn = n.val;
if(ss.contains(k-nn)){
return true;
}
ss.add(nn);
if(n.left!=null){
q.offer(n.left);
}
if(n.right!=null){
q.offer(n.right);
}
}
}
return false;
}
}