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 email@example.com. 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- K-th ancestor of a node in Binary Tree | Set 3
- K-th ancestor of a node in Binary Tree
- Maximum difference between node and its ancestor in Binary Tree
- Kth ancestor of a node in an N-ary tree using Binary Lifting Technique
- 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)
- Least Common Ancestor of any number of nodes in Binary Tree
- Construct Binary Tree from Ancestor Matrix | Top Down Approach
- Lowest Common Ancestor in a Binary Search Tree.
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Get Level of a node in a Binary Tree
- Search a node in Binary Tree
- Sum of cousins of a given node in a Binary Tree
- Total sum except adjacent of a given node in a Binary Tree
- Preorder Successor of a Node in Binary Tree
- Find mirror of a given node in Binary tree
- Print cousins of a given node in Binary Tree
- Delete the last leaf node in a Binary Tree
- Replace node with depth in a binary tree