Skip to content

Commit c8634b1

Browse files
Add files via upload
1 parent cf24dd9 commit c8634b1

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
public class Solution {
2+
3+
public static void nodesAtDistanceK(BinaryTreeNode<Integer> root, int node, int k) {
4+
//Your code goes here
5+
print(root,node,k);
6+
7+
8+
}
9+
10+
private static int print(BinaryTreeNode<Integer> root, int node, int k)
11+
{
12+
//If tree is empty return -1
13+
if (root==null)
14+
return -1;
15+
16+
int rootData=root.data;
17+
if (rootData==node)
18+
{
19+
printNodesAtDistanceK(root, k);
20+
return 0;
21+
}
22+
23+
int leftSubTreeDist=0,rightSubTreeDist=0;
24+
25+
leftSubTreeDist=print(root.left,node,k);
26+
if (leftSubTreeDist!=-1)
27+
{
28+
if(leftSubTreeDist+1==k)
29+
{
30+
System.out.println(rootData);
31+
}
32+
else
33+
{
34+
rightSubTreeDist=k-(leftSubTreeDist+1)-1;
35+
printNodesAtDistanceK(root.right, rightSubTreeDist);
36+
}
37+
return leftSubTreeDist+1;
38+
}
39+
40+
rightSubTreeDist=print(root.right,node,k);
41+
if (rightSubTreeDist!=-1)
42+
{
43+
if(rightSubTreeDist+1==k)
44+
{
45+
System.out.println(rootData);
46+
}
47+
else
48+
{
49+
leftSubTreeDist=k-(rightSubTreeDist+1)-1;
50+
printNodesAtDistanceK(root.left, leftSubTreeDist);
51+
}
52+
return rightSubTreeDist+1;
53+
}
54+
return -1;
55+
}
56+
57+
private static void printNodesAtDistanceK(BinaryTreeNode<Integer> root, int k)
58+
{
59+
if (root==null || k<0)
60+
return;
61+
62+
if (k == 0)
63+
{
64+
System.out.println(root.data);
65+
return;
66+
}
67+
68+
printNodesAtDistanceK(root.left,k-1);
69+
printNodesAtDistanceK(root.right,k-1);
70+
}
71+
72+
}

0 commit comments

Comments
 (0)