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:
- Kth ancestor of a node in binary tree | Set 2
- 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 3 (Using RMQ)
- Lowest Common Ancestor in a Binary Tree | Set 1
- Construct Ancestor Matrix from a Given Binary Tree
- 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
- Sum of cousins of a given node in a Binary Tree
- Search a node in Binary Tree
- Kth node in Diagonal Traversal of Binary Tree
- Replace node with depth in a binary tree
- Closest leaf to a given node in Binary Tree
- Postorder successor of a Node in 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.
Improved By : rituraj_jain