-
Notifications
You must be signed in to change notification settings - Fork 1
/
KDistanceFromRoot.java
52 lines (46 loc) · 1.05 KB
/
KDistanceFromRoot.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
//User function Template for Java
/*
class Node
{
int data;
Node left, right;
Node(int item) {
data = item;
left = right = null;
}
} */
class Tree
{
// Recursive function to print right view of a binary tree.
ArrayList<Integer> Kdistance(Node root, int k)
{
ArrayList<Integer> ans = new ArrayList<>();
if(root==null)
return new ArrayList<>();
if(k==0) {
ans.add(root.data);
return ans;
}
Queue<Node> q = new LinkedList<>();
int count = 0;
q.offer(root);
while(!q.isEmpty()) {
int sz = q.size();
if(count == k) {
while(sz-->0) {
ans.add(q.poll().data);
}
break;
}
else {
while(sz-->0) {
Node node = q.poll();
if(node.left!=null) q.offer(node.left);
if(node.right!=null) q.offer(node.right);
}
}
count++;
}
return ans;
}
}