Problem
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 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)
return thekth
ancestor of the given nodenode
. If there is no such ancestor, return-1
.
Examples
Example 1
|
|
Constraints
1 <= k <= n <= 5 * 104
parent.length == n
parent[0] == -1
0 <= parent[i] < n
for all0 < i < n
0 <= node < n
- There will be at most
5 * 104
queries.
Solution
Method 1 – Binary Lifting (Dynamic Programming)
Intuition
Precompute ancestors for each node at powers of two distances, so we can jump up the tree in logarithmic steps. This allows efficient queries for the kth ancestor.
Approach
- Build a table
up[node][j]
whereup[node][j]
is the 2^j-th ancestor ofnode
. - For each query, repeatedly jump up by the largest possible power of two less than or equal to
k
. - If at any point the ancestor is -1, return -1.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(log n)
per query,O(n log n)
preprocessing. Each query jumps up the tree in logarithmic steps. - 🧺 Space complexity:
O(n log n)
for ancestor table.