Skip to content

Practice Kth Ancestor of a Tree Node

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Problem Statement

TreeAncestor(n,parent) receives a tree rooted at node 0. getKthAncestor(node,k) returns the node reached after k parent steps, or -1 if the path reaches beyond the root. parent[0] is -1; all other entries identify valid parents. Practice approach: Precompute ancestors at distances 1,2,4,... using binary lifting. For each set bit of k, jump through the corresponding table column, stopping at -1. Preprocessing costs O(n log n), queries O(log n), and storage O(n log n). Test asking for an ancestor of the root and a distance greater than the node's depth.

Source: Kth Ancestor of a Tree Node on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["TreeAncestor","getKthAncestor","getKthAncestor","getKthAncestor"]
[[5,[-1,0,0,1,3]],[4,2],[4,3],[2,2]]
Output
[null,1,0,-1]
Explanation

The path from 4 is 4→3→1→0. Node 2 has only one ancestor.

Constraints

1 <= k <= n <= 5 * 10^4
parent.length == n
parent[0] == -1
0 <= parent[i] < n for i > 0
0 <= node < n
At most 5 * 10^4 queries.

Related LeetCode Problems

Practice more problems similar to Kth Ancestor of a Tree Node.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.