-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain56.java
More file actions
44 lines (41 loc) · 1.11 KB
/
Main56.java
File metadata and controls
44 lines (41 loc) · 1.11 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
package JZOfferTuJi;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;
// 深度优先遍历
public class Main56 {
Set<Integer> set = new HashSet<>();
public boolean findTarget(TreeNode root, int k) {
if(root == null) {
return false;
}
if(set.contains(k - root.val)) {
return true;
}
set.add(root.val);
return findTarget(root.left, k) || findTarget(root.right, k);
}
}
// 广度优先遍历
class Main56_1 {
public boolean findTarget(TreeNode root, int k) {
Set<Integer> set = new HashSet<>();
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode temp = queue.poll();
if(set.contains(k - temp.val)) {
return true;
}
set.add(temp.val);
if(temp.left != null) {
queue.add(temp.left);
}
if(temp.right != null) {
queue.add(temp.right);
}
}
return false;
}
}