-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclosetLeaf.java
More file actions
55 lines (52 loc) · 1.82 KB
/
closetLeaf.java
File metadata and controls
55 lines (52 loc) · 1.82 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
import java.util.*;
public class closetLeaf {
// step1: dfs traverse the tree to find the target node and build parent hashmap
// step2: bfs traverse the graph, find the closest leaf
HashMap<TreeNode, TreeNode> map;
TreeNode target;
public int findClosestLeaf(TreeNode root, int k) {
// step 1
map = new HashMap<>();
target = null;
dfs(root, null, k);
// step 2
Queue<TreeNode> queue = new LinkedList<>();
Set<TreeNode> visited = new HashSet<>();
// 注意这里的细节,是add 进queue里面的时候标记为visited
queue.add(target);
visited.add(target);
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode cur = queue.remove();
if(cur.left == null && cur.right == null) {
return cur.val;
}
// 3 directions
// left
if(cur.left != null && !visited.contains(cur.left)){
queue.add(cur.left);
visited.add(cur.left);
}
// right
if(cur.right != null && !visited.contains(cur.right)){
queue.add(cur.right);
visited.add(cur.right);
}
// parent
if(map.get(cur) != null && !visited.contains(map.get(cur))){
queue.add(map.get(cur));
visited.add(map.get(cur));
}
}
}
return -1;
}
private void dfs(TreeNode root, TreeNode parent, int k){
if(root == null) return;
if(root.val == k) target = root;
map.put(root, parent);
dfs(root.left, root, k);
dfs(root.right, root, k);
}
}