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.
Approach: First we find the path of given key data from the root and we will store it into a vector then we simply return the kth index of the vector from the last.
Below is the implementation of the above approach:
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 binary tree | Set 2
- Kth ancestor of a node in an N-ary tree using Binary Lifting Technique
- Kth ancestor of all nodes in an N-ary tree using DFS
- Maximum difference between node and its ancestor in Binary Tree
- K-th ancestor of a node in Binary Tree
- Lowest Common Ancestor in a Binary Tree | Set 1
- 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 Search Tree.
- Construct Ancestor Matrix from a Given Binary Tree
- Least Common Ancestor of any number of nodes in Binary Tree
- Construct Binary Tree from Ancestor Matrix | Top Down Approach
- 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
- Query for ancestor-descendant relationship in a tree
- Construct tree from ancestor matrix
- 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
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.