# Print nodes at K distance from root in binary tree

In a binary tree, given a root and a number K. You have to find the all nodes at distance K from given root node.

For example in a given tree, if K =2 then Output should be 4,5,6
if k = 1 then Output should be 2,3

```// structure of tree
struct node
{
int value;
struct node* left;
struct node* right;
};

// function to print nodes at k distance
void kDistanceNodes(Node *root , int k)
{
if(root == NULL || k < 0)
return;

if( k == 0 )
printf("%d", root->value );
else
{
kDistanceNodes(root->left, k-1 ) ;
kDistanceNodes(root->right, k-1 ) ;
}
}
```

Time complexity: O(N) as we have to traverse the compelete tree, N is the number of nodes in a tree

### 2 Thoughts on “Print nodes at K distance from root in binary tree”

1. Rajiur Rahman on September 16, 2015 at 10:43 am said:

Hi
Just though to give iterative manner a try. I was thinking initially it should be very easy, but struggled to get working correctly. My java method code snippet is following.

public static void nodeAtKDistance(Node root, int distance){ //assume dist is not more than tree height
if(distance == 1){
System.out.println(root.getData());
}
else{
for(int i=1; i<distance; i++){
if( (i & 1) != 0){ // for i==odd
while(!treeQueue1.isEmpty()){
System.out.println("Hello");
Node current = treeQueue1.poll();
}
}
else{ //for i==even
while(!treeQueue2.isEmpty()){
System.out.println("Hi");
Node current = treeQueue2.poll();
}
}
}
}
if( (distance & 1) == 0 ){ //distance value is even, pop all the values from TreeQueue1
while(!treeQueue2.isEmpty()){
Node temp = treeQueue2.poll();
System.out.print(temp.getData() + " ");
}
}
else{
while(!treeQueue1.isEmpty()){
Node temp = treeQueue1.poll();
System.out.print(temp.getData() + " ");
}
}
}

2. void printNodesAtDistanceK(node *root,int level,int k) {
if (!root)
return;
else if (level == k) {
cout<val<left,level + 1,k);
printNodesAtDistanceK(root->right,level + 1,k);
}
}