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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Kth ancestor of a node in an N-ary tree using Binary Lifting Technique
- K-th ancestor of a node in Binary Tree | Set 3
- Kth ancestor of all nodes in an N-ary tree using DFS
- K-th ancestor of a node in Binary Tree
- Maximum difference between node and its ancestor in Binary Tree
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
- Lowest Common Ancestor in a Binary Tree | Set 1
- Lowest Common Ancestor in a Binary Search Tree.
- Least Common Ancestor of any number of nodes in Binary Tree
- Construct Binary Tree from Ancestor Matrix | Top Down Approach
- Construct Ancestor Matrix from a Given Binary Tree
- Lowest Common Ancestor for a Set of Nodes in a Rooted Tree
- Kth node in Diagonal Traversal of Binary Tree
- Find the kth node in vertical order traversal of a Binary Tree
- Construct tree from ancestor matrix
- Query for ancestor-descendant relationship in a tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Prime Numbers present at Kth level of a Binary Tree