forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_742.java
73 lines (68 loc) · 2.49 KB
/
_742.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
68
69
70
71
72
73
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class _742 {
public static class Solution1 {
public int findClosestLeaf(TreeNode root, int k) {
Map<Integer, Set<Integer>> graph = new HashMap<>();
Set<Integer> leaves = new HashSet<>();
buildGraph(root, graph, null, leaves);
if (leaves.contains(k)) {
return k;
}
//Now we can do a BFS traversal
Queue<Integer> queue = new LinkedList<>();
Set<Integer> directNeighbors = graph.get(k);
Set<Integer> visited = new HashSet<>();//use a visited set to prevent cycles and not adding the target node itself
visited.add(k);
for (int node : directNeighbors) {
queue.offer(node);
visited.add(node);
}
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int curr = queue.poll();
if (leaves.contains(curr)) {
return curr;
}
Set<Integer> nextNodes = graph.get(curr);
for (int next : nextNodes) {
if (!visited.contains(next)) {
queue.offer(next);
visited.add(next);
}
}
}
}
return root.val;
}
private void buildGraph(TreeNode root, Map<Integer, Set<Integer>> map, TreeNode parent, Set<Integer> leaves) {
if (root == null) {
return;
}
if (!map.containsKey(root.val)) {
map.put(root.val, new HashSet<>());
}
if (root.left != null) {
map.get(root.val).add(root.left.val);
}
if (root.right != null) {
map.get(root.val).add(root.right.val);
}
if (parent != null) {
map.get(root.val).add(parent.val);
}
if (root.left == null && root.right == null) {
leaves.add(root.val);
}
buildGraph(root.left, map, root, leaves);
buildGraph(root.right, map, root, leaves);
}
}
}