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.
Kth Ancestor of a Tree Node
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
["TreeAncestor","getKthAncestor","getKthAncestor","getKthAncestor"] [[5,[-1,0,0,1,3]],[4,2],[4,3],[2,2]]
[null,1,0,-1]
The path from 4 is 4→3→1→0. Node 2 has only one ancestor.
Constraints
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.