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 the kth ancestor of the given node. 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
Kth Ancestor Problem: Tree Structure and Queries0root123456Sample QueriesgetKthAncestor(3, 1) → 1Path: 3 → 1 (1 step)getKthAncestor(5, 2) → 0Path: 5 → 2 → 0 (2 steps)getKthAncestor(6, 3) → 0Path: 6 → 2 → 0 (2 steps max)getKthAncestor(4, 5) → -1Not enough ancestors availableBinary lifting enables O(log k) queries
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
Asked in
Google 28 Facebook 15 Amazon 12
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen