Print the nodes at k distance from the root of a binary tree

In this tutorial we shall see how to print all the nodes that is k distance from root.

Problem statement:

Given the root node and the distance k, print all the nodes that are at distance k from root node.
Consider the image below:
print_all_nodes_at_k_distance_from_root
So according to the image, root is at level 0, below that is level 1 etc.
So if the k value is 3, then you need to print h, i, j, k.
If the k value is 1, you need to print b, c.

So how do we solve this?

First base cases will be:
1. If the node becomes null, then we return.
2. If the k value becomes 0, we return the value pointed by the node.
Then we make a recursive call to both left and right child. While doing a recursive call, we decrease the k value.

Pseudo Code:

void get_k_node(node *p, int k)
{
	if (p == NULL)
		return ;

	if (k == 0)
		print p -> value

	else
	{
		get_k_node(p->left)
		get_k_node(p->right)
	}
}

The recursion tree when k = 2 will be like below:

print_all_nodes_at_k_distance_from_root

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *