Given a binary tree in which nodes are numbered from 1 to n. Given a node and a positive integer K. We have to print the Kth ancestor of the given node in the binary tree. If there does not exist any such ancestor then print -1.
For example in the below given binary tree, 2nd ancestor of node 4 and 5 is 1. 3rd ancestor of node 4 will be -1.
We have discussed a BFS based solution for this problem in our previous article. If you observe that solution carefully, you will see that the basic approach was to first find the node and then backtrack to the kth parent. The same thing can be done using recursive DFS without using an extra array.
The idea of using DFS is to first find the given node in the tree, and then backtrack k times to reach to kth ancestor, once we have reached to the kth parent, we will simply print the node and return NULL.
Below is the implementation of above idea:
Kth ancestor is: 1
Time Complexity : O(n), where n is the number of nodes in the binary tree.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- K-th ancestor of a node in Binary Tree
- K-th ancestor of a node in Binary Tree | Set 3
- Kth ancestor of a node in an N-ary tree using Binary Lifting Technique
- Maximum difference between node and its ancestor in Binary Tree
- Lowest Common Ancestor in a Binary Tree | Set 1
- Construct Ancestor Matrix from a Given Binary Tree
- Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
- Lowest Common Ancestor in a Binary Search Tree.
- Construct Binary Tree from Ancestor Matrix | Top Down Approach
- Least Common Ancestor of any number of nodes in Binary Tree
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Get Level of a node in a Binary Tree
- Sum of cousins of a given node in a Binary Tree
- Search a node in Binary Tree
- Inorder Successor of a node in Binary Tree