-
Notifications
You must be signed in to change notification settings - Fork 116
/
BST and Binary Tree Assignment::Print nodes at distance k from node
68 lines (57 loc) · 1.57 KB
/
BST and Binary Tree Assignment::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
public class Solution {
/* Binary Tree Node class
*
* class BinaryTreeNode<T> {
T data;
BinaryTreeNode<T> left;
BinaryTreeNode<T> right;
public BinaryTreeNode(T data) {
this.data = data;
}
}
*/
public static void nodesAtDistanceK(BinaryTreeNode<Integer> root, int node, int k) {
// Write your code here
int x = print(root,k,node);
}
public static int print(BinaryTreeNode<Integer> root,int k,int elem){
if(root == null){
return -1;
}
if(root.data == elem){
printAtDepthK(root,k);
return 0;
}
int ld = print(root.left,k,elem);
int rd;
if(ld == -1){
rd = print(root.right,k,elem);
if(rd == -1){
return -1;
}else if(rd + 1 == k){
System.out.println(root.data+" ");
return k;
}else{
printAtDepthK(root.left,k-rd-2);
return rd+1;
}
}else if(ld + 1 == k){
System.out.println(root.data+" ");
return k;
}else{
printAtDepthK(root.right,k-ld-2);
return ld+1;
}
}
public static void printAtDepthK(BinaryTreeNode<Integer> root,int depth){
if(root == null){
return;
}
if(depth == 0 && root != null){
System.out.println(root.data+" ");
return;
}
printAtDepthK(root.left,depth-1);
printAtDepthK(root.right,depth-1);
}
}