Given a binary tree, write an efficient algorithm to find all nodes present at a given distance from any leaf node. We need to find only those nodes that are present in the root-to-leaf path for that leaf.

For example, consider the following binary tree:

 
Find nodes at a given distance from leaf nodes

The nodes present at a distance of 1 from any leaf node are 10, 16, 20
The nodes present at a distance of 2 from any leaf node are 15, 20
The nodes present at a distance of 3 from any leaf node is 15

Practice this problem

The idea is to traverse the tree in a preorder fashion and use a list to store the current node’s ancestors in the preorder traversal. If we encounter a leaf node, print the ancestor present at a given distance from it. To avoid printing duplicates, insert the nodes into a set and print it later.

Following is the implementation of the idea in C++, Java, and Python:

C++


Download  Run Code

Output:

10 16 20

Java


Download  Run Code

Output:

10 16 20

Python


Download  Run Code

Output:

[16, 10, 20]

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the binary tree.