Given a binary tree of size n, along with a node and a positive integer k, find the k-th ancestor of the given node in the binary tree. If such an ancestor does not exist, return -1.
Note: It is guaranteed that the node exists in the tree and all the nodes of the tree have distinct values.
Output: 1 Explanation: Since, k is 2 and node is 4, so we first need to locate the node and look k times its ancestors. In this case, node 4 has 1 as its 2nd ancestor, which is the root of the tree.
Input: k=1, node=3 π Image Output: 1 Explanation: k = 1 and node = 3, k-th ancestor of node 3 is 1.
Using Hash Map & Level Order Traversal - O(n) Time and O(n) Space
This idea is to find the k-th ancestor by first storing the parent of every node in a map using level order traversal (BFS). Once we know each nodeβs direct parent, we can easily move upward from the given node step-by-step. By repeating this process k times (or until the root is reached), we reach the required k-th ancestor efficiently.
Once the parent map is built, the k-th ancestor can be found as:
1st ancestor = parent[i]
2nd ancestor = parent[parent[i]]
3rd ancestor = parent[parent[parent[i]]]
β¦
k-th ancestor = applying parent[] k times on node i
Perform BFS and store each nodeβs parent: parent[1] = -1, parent[2] = 1, parent[3] = 1, parent[4] = 2, parent[5] = 2.
Start from given node = 4 with k = 2.
First move: go to parent from 4 to 2, now k = 1.
Second move: go to parent from 2 to 1, now k = 0.
When k becomes 0, current node 1 is the k-th ancestor.
Output
1
Using Recursive Backtracking - O(n) Time and O(n) Space
The idea is to traverse the tree using recursion to first locate the target node and then trace back toward the root. During this backtracking phase, we decrease the value of k at each step as we move up through its ancestors. When k becomes 0, the current node at that point is the k-th ancestor.