Given a binary tree, find all ancestors of a given node in it.

For example, consider the following binary tree:

 
Root To Leaf Paths in Binary Tree

The ancestor of node 9 are 7, 3 and 1
The ancestor of node 6 is 3 and 1
The ancestor of node 5 is 2 and 1
… …

Practice this problem

Recursive Solution

The idea is to traverse the tree in a postorder fashion and search for a given node in the tree. For any node, if the given node is found in either its left subtree or its right subtree, then the current node is an ancestor of it. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

5 3 1

Java


Download  Run Code

Output:

5 3 1

Python


Download  Run Code

Output:

5 3 1

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The program requires O(h) extra space for the call stack, where h is the height of the tree.

Iterative Solution

The idea is to maintain a map to store the parent node of all nodes present in the tree. Then perform an iterative preorder traversal on the tree and set the parent pointer of each node. Finally, print ancestors of the given key by using a parent map.

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

C++


Download  Run Code

Output:

5 3 1

Java


Download  Run Code

Output:

5 3 1

Python


Download  Run Code

Output:

5 3 1

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.