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,-1]
💡 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 -1 (6 only has 2 ancestors: 2 and 0, so 3rd ancestor doesn't exist)
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 of a Tree Node INPUT 0 1 2 3 4 5 6 n = 7 parent=[-1,0,0,1,1,2,2] Queries: [3,1], [5,2], [6,3] (node, k) ALGORITHM STEPS 1 Build Jump Table up[i][j] = 2^j ancestor node | 2^0 | 2^1 3 | 1 | 0 5 | 2 | 0 6 | 2 | 0 ... 2 Query Processing Use binary of k to jump 3 Example: node=6, k=3 k=3 = 11 binary 4 Jump Sequence 6 --2^0--> 2 --2^1--> 0 Query Traces: [3,1]: 3-->1 (1 jump) [5,2]: 5-->2-->0 (2 jumps) [6,3]: 6-->2-->0 (3 jumps) FINAL RESULT 0 1 2 3 4 5 6 Output: [1, 0, 0] Results Verified: getKthAncestor(3,1) = 1 OK getKthAncestor(5,2) = 0 OK getKthAncestor(6,3) = 0 OK Key Insight: Binary Lifting precomputes 2^j ancestors for each node in O(n log n) time. Each query uses binary representation of k to make O(log k) jumps instead of k steps. Time: O(n log n) preprocessing + O(log k) per query | Space: O(n log n) for jump table TutorialsPoint - Kth Ancestor of a Tree Node | Binary Lifting Approach
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