Skip to content

Commit bed0bd2

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 863_All_Nodes_Distance_K_in_Binary_Tree.java
1 parent 6b125d1 commit bed0bd2

File tree

1 file changed

+40
-35
lines changed

1 file changed

+40
-35
lines changed
Lines changed: 40 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,65 @@
11
class Solution {
22
public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
3-
Map<TreeNode, TreeNode> hm = buildParentMap(root);
4-
Set<TreeNode> visited = new HashSet<>();
3+
if (root == null) {
4+
return Collections.emptyList();
5+
}
6+
57
List<Integer> result = new ArrayList<>();
8+
Map<Integer, Set<Integer>> graph = new HashMap<>();
9+
buildGraph(root, graph);
610

7-
Queue<TreeNode> q = new LinkedList<>();
8-
q.offer(target);
9-
visited.add(target);
11+
Set<Integer> visited = new HashSet<>();
12+
Queue<Integer> q = new LinkedList<>();
13+
q.offer(target.val);
1014

11-
while (K > 0) {
12-
int levelSize = q.size();
15+
while (K >= 0) {
16+
int level = q.size();
1317

14-
for (int i = 0; i < levelSize; i++) {
15-
TreeNode t = q.poll();
18+
for (int i = 0; i < level; i++) {
19+
int node = q.poll();
1620

17-
if (t.left != null && visited.add(t.left)) {
18-
q.offer(t.left);
21+
if (visited.contains(node)) {
22+
continue;
1923
}
20-
if (t.right != null && visited.add(t.right)) {
21-
q.offer(t.right);
24+
visited.add(node);
25+
26+
if (K == 0) {
27+
result.add(node);
2228
}
2329

24-
if (hm.get(t) != null && visited.add(hm.get(t))) {
25-
q.offer(hm.get(t));
30+
for (int neighbour : graph.get(node)) {
31+
q.offer(neighbour);
2632
}
2733
}
2834

29-
--K;
30-
}
31-
32-
for (TreeNode t : q) {
33-
result.add(t.val);
35+
K--;
3436
}
3537

3638
return result;
3739
}
3840

39-
private Map<TreeNode, TreeNode> buildParentMap(TreeNode root) {
40-
Map<TreeNode, TreeNode> hm = new HashMap<>();
41-
Queue<TreeNode> q = new LinkedList<>();
42-
q.offer(root);
41+
private void buildGraph(TreeNode root, Map<Integer, Set<Integer>> graph) {
42+
if (root == null) {
43+
return;
44+
}
4345

44-
while (!q.isEmpty()) {
45-
TreeNode t = q.poll();
46+
graph.putIfAbsent(root.val, new HashSet<>());
4647

47-
if (t.left != null) {
48-
hm.put(t.left, t);
49-
q.offer(t.left);
50-
}
48+
if (root.left != null) {
49+
graph.putIfAbsent(root.left.val, new HashSet<>());
5150

52-
if (t.right != null) {
53-
hm.put(t.right, t);
54-
q.offer(t.right);
55-
}
51+
graph.get(root.val).add(root.left.val);
52+
graph.get(root.left.val).add(root.val);
53+
}
54+
55+
if (root.right != null) {
56+
graph.putIfAbsent(root.right.val, new HashSet<>());
57+
58+
graph.get(root.val).add(root.right.val);
59+
graph.get(root.right.val).add(root.val);
5660
}
5761

58-
return hm;
62+
buildGraph(root.left, graph);
63+
buildGraph(root.right, graph);
5964
}
6065
}

0 commit comments

Comments
 (0)