You're building a family tree navigation system that can quickly find any ancestor at a specific generation level. Given a tree with n nodes numbered from 0 to n-1 and a parent array where parent[i] represents the parent of node i, you need to efficiently answer queries about the kth ancestor of any node.
The kth ancestor of a node is the node that appears k steps up in the path from that node to the root. For example, if we trace the path from a node to the root, the 1st ancestor is its parent, the 2nd ancestor is its grandparent, and so on.
Your task: Implement a TreeAncestor class that can handle multiple queries efficiently:
TreeAncestor(int n, int[] parent)- Initialize with the tree structureint getKthAncestor(int node, int k)- Return the kth ancestor of the given node, or-1if no such ancestor exists
Since there can be up to 50,000 queries, a naive approach of traversing up the tree each time will be too slow. You'll need to use preprocessing techniques like binary lifting or dynamic programming to achieve optimal performance.
Input & Output
Constraints
- 1 โค n โค 5 ร 104
- parent[0] == -1 indicating that 0 is the root
- 0 โค parent[i] < n for all 0 < i < n
- 0 โค node < n
- 1 โค k โค n
- At most 5 ร 104 queries will be made