Print Nodes at K distance from Root in Binary Tree

Print nodes at K distance from root in binary tree. ORPrint nodes at Level K.

Given a Binary Tree, Print all Nodes that are at K distance from root node in Binary Tree. We can also think of this question as Print all nodes that belong to Level K.

Lets understand what will be input and expected output with the help of an example.

If k = 2. It means we need to print all nodes that are at distance 2 from Root node.
It also means we need to print all nodes at Level 2, because all Nodes of Level 2 will be at same distance from Root Node.

Algorithm

It is very easy and just require Pre-order traversal of Tree.
If you are not familar with Pre order traversal, I would suggest to have a look at Pre-order traversal first: Pre-Order Traversal of Binary Tree

1. Do a Pre-Order traversal of Tree and and decrement K each time you move to left or right.
2. When K = 0, it means that is the level we are interested in.
So print the Node and return.

Note:  Once we reach k = 0, no need to further explore the tree down, because we already reached the level that we are interested in, So going ahead is of no use.

Java Program to Print Nodes at K distance from Root.

```public class PrintNodesAtKDistanceFromRoot {

public static void main(String[] args) {
new PrintNodesAtKDistanceFromRoot();
}

public PrintNodesAtKDistanceFromRoot(){

Node rootNode=null;

printNodesAtLevel(rootNode, 0);
}

private void printNodesAtLevel(Node rootNode, int level) {
if(rootNode==null){
return;
}

if(level == 0){
System.out.print(rootNode.getData() + " ");
return;
}

printNodesAtLevel(rootNode.getLeft(), level - 1);
printNodesAtLevel(rootNode.getRight(), level - 1);
}

private Node addNode(Node rootNode, int i) {
if(rootNode==null){
return new Node(i);
}else{
if(i > rootNode.getData()){

}else{
}
}
return rootNode;
}
}

```