In last article we saw how can we print the height of the binary tree . In this article we will see how can we print the nodes at distance.
So here in the image you can see we have a binary tree. You have to print the nodes at distance 0
In this image we can clearly see that the node at distance 0 is 1 so our output must be 1.
So now we are going to implement a Java code for this problem.
Java Code :
class Node{
int data;
Node left;
Node right;
Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}
class HindiCodingCommunity{
public static void printkth(Node root,int k){
if(root==null){
return;
}
if(k==0){
System.out.println(root.data);
}
else{
printkth(root.left,k-1);
printkth(root.right,k-1);
}
}
public static void main(String args[])
{
Node root = new Node(1);
root.left = new Node(2);
root.right= new Node(3);
root.left.left= new Node(4);
root.right.left= new Node(5);
root.right.right= new Node(6);
printkth(root);
}
}
Time Complexity : O(n)
Auxilary Space : theta(h)