Kth Ancestor of a Tree Node - Problem
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the ith node. The root of the tree is node 0. Find the kth ancestor of a given node.
The kth ancestor of a tree node is the kth node in the path from that node to the root node.
Implement the TreeAncestor class:
TreeAncestor(int n, int[] parent)- Initializes the object with the number of nodes in the tree and the parent array.int getKthAncestor(int node, int k)- Returns thekthancestor of the givennode. If there is no such ancestor, return-1.
Input & Output
Example 1 — Basic Ancestor Query
$
Input:
n = 7, parent = [-1,0,0,1,1,2,2], operations = [[3,1],[5,2],[6,3]]
›
Output:
[1,0,0]
💡 Note:
TreeAncestor(7, [-1,0,0,1,1,2,2]) creates the tree. getKthAncestor(3,1) returns 1 (parent of 3), getKthAncestor(5,2) returns 0 (grandparent of 5), getKthAncestor(6,3) returns 0 (great-grandparent of 6)
Example 2 — No Such Ancestor
$
Input:
n = 5, parent = [-1,0,0,1,2], operations = [[4,3],[2,4]]
›
Output:
[-1,-1]
💡 Note:
Node 4's path to root is 4→2→0 (only 2 ancestors), so 3rd ancestor doesn't exist. Node 2's path is 2→0 (only 1 ancestor), so 4th ancestor doesn't exist
Example 3 — Root Ancestor Query
$
Input:
n = 3, parent = [-1,0,1], operations = [[2,1],[2,2],[0,1]]
›
Output:
[1,0,-1]
💡 Note:
getKthAncestor(2,1) = 1 (parent of 2), getKthAncestor(2,2) = 0 (grandparent of 2), getKthAncestor(0,1) = -1 (root has no parent)
Constraints
- 1 ≤ n ≤ 5 × 104
- parent[0] == -1
- 0 ≤ parent[i] < n for i > 0
- 1 ≤ k ≤ 5 × 104
- At most 5 × 104 queries
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Tree with parent array [-1,0,0,1,1,2,2]
2
Query Processing
Find kth ancestor using binary lifting
3
Output
Return ancestor node or -1 if not found
Key Takeaway
🎯 Key Insight: Binary lifting precomputes 2^i ancestors to answer any kth ancestor query in logarithmic time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code