-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAll Nodes Distance K in Binary Tree.java
More file actions
77 lines (64 loc) · 1.81 KB
/
All Nodes Distance K in Binary Tree.java
File metadata and controls
77 lines (64 loc) · 1.81 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Pair{
int val;
int dist;
Pair(int val,int dist){
this.val = val;
this.dist = dist;
}
}
class Solution {
public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
List<List<Integer>> graph = new ArrayList<>();
int[] visited = new int[501];
for(int i=1;i<=500;i++){
graph.add(new ArrayList<>());
}
dfs(root,graph);
Queue<Pair> q = new LinkedList<>();
q.add(new Pair(target.val,0));
List<Integer> result = new ArrayList<>();
while(!q.isEmpty()){
Pair curr = q.poll();
int val = curr.val;
int dist = curr.dist;
visited[val] = 1;
if(dist == k){
result.add(val);
continue;
}
List<Integer> edges = graph.get(val);
for(int i=0;i<edges.size();i++){
int edge = edges.get(i);
if(visited[edge] == 0){
q.add(new Pair(edge,dist + 1));
}
}
}
return result;
}
public void dfs(TreeNode root,List<List<Integer>> graph){
int rootVal = root.val;
if(root.left != null){
int leftVal = root.left.val;
graph.get(rootVal).add(leftVal);
graph.get(leftVal).add(rootVal);
dfs(root.left,graph);
}
if(root.right != null){
int rightVal = root.right.val;
graph.get(rootVal).add(rightVal);
graph.get(rightVal).add(rootVal);
dfs(root.right,graph);
}
return;
}
}