-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Trees2-Print nodes at distance k from node
94 lines (83 loc) · 2.29 KB
/
Binary Trees2-Print nodes at distance k from node
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
You are given a Binary Tree of type integer, a target node, and an integer value K.
Print the data of all nodes that have a distance K from the target node. The order in which they would be printed will not matter.
Example:
For a given input tree(refer to the image below):
1. Target Node: 5
2. K = 2
alt txt
Starting from the target node 5, the nodes at distance K are 7 4 and 1.
Input Format:
The first line of input will contain the node data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data.
The second line of input contains two integers separated by a single space, representing the value of the target node and K, respectively.
Output Format:
All the node data at distance K from the target node will be printed on a new line.
The order in which the data is printed doesn't matter.
Constraints:
1 <= N <= 10^5
Where N is the total number of nodes in the binary tree.
Time Limit: 1 sec
Sample Input 1:
5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1
3 1
Sample Output 1:
9
6
Sample Input 2:
1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1
3 3
Sample Output 2:
4
5
****************************************Solution********************************************
public static void nodesAtDistanceK(BinaryTreeNode<Integer> root, int node, int k) {
print(root,node,k);
}
private static int print(BinaryTreeNode<Integer> root,int node,int k)
{
if(root==null)
return -1;
int rootData=root.data;
if(rootData==node)
{
printDistance(root,k);
return 0;
}
int leftDist=0,rightDist=0;
leftDist=print(root.left,node,k);
if(leftDist!=-1)
{
if(leftDist+1==k)
{
System.out.println(rootData);
}
else{
rightDist=k-(leftDist+1)-1;
printDistance(root.right, rightDist);
}
return leftDist+1;
}
rightDist=print(root.right,node,k);
if(rightDist!=-1)
{
if(rightDist+1==k)
System.out.println(rootData);
else{
leftDist=k-(rightDist+1)-1;
printDistance(root.left, leftDist);
}
return rightDist+1;
}
return -1;
}
private static void printDistance(BinaryTreeNode<Integer> root, int k)
{
if(root==null || k<0)
return;
if(k==0)
{
System.out.println(root.data);
return;
}
printDistance(root.left, k-1);
printDistance(root.right, k-1);
}