Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.
For example, consider the following Binary Tree
1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10
Following are different input keys and their ancestors in the above tree
Input Key List of Ancestors ------------------------- 1 2 1 3 1 4 2 1 5 2 1 6 3 1 7 3 1 8 4 2 1 9 5 2 1 10 7 3 1
Recursive solution for this problem is discussed here.
It is clear that we need to use a stack based iterative traversal of the Binary Tree. The idea is to have all ancestors in stack when we reach the node with given key. Once we reach the key, all we have to do is, print contents of stack.
How to get all ancestors in stack when we reach the given node? We can traverse all nodes in Postorder way. If we take a closer look at the recursive postorder traversal, we can easily observe that, when recursive function is called for a node, the recursion call stack contains ancestors of the node. So idea is do iterative Postorder traversal and stop the traversal when we reach the desired node.
Following is implementation of the above approach.
Following are all keys and their ancestors 1: 2: 1 3: 1 4: 2 1 5: 2 1 6: 3 1 7: 3 1 8: 4 2 1 9: 5 2 1 10: 7 3 1
Note that the above solution assumes that the given key is present in the given Binary Tree. It may go in infinite loop if key is not present. Extend the above solution to work even when the key is not present in tree.
This article is contrubuted by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Iterative method to find ancestors of a given binary tree
- Print leaf nodes in binary tree from left to right using one stack
- Inorder Tree Traversal without Recursion
- Construct Binary Tree from String with bracket representation
- Modify a binary tree to get preorder traversal using right pointers only
- Check if a given array can represent Preorder Traversal of Binary Search Tree
- Count all Grandparent-Parent-Child Triplets in a binary tree whose sum is greater than X
- Reverse a stack using recursion
- Sort a stack using recursion
- One97 Interview Experience | Set 3 (Backend/Node js Developer)
- Print Bracket Number
- Print Stack Elements from Bottom to Top
- Print next greater number of Q queries
- Print Reverse a linked list using Stack
- ZigZag Tree Traversal
Improved By : shrikanth13