Class TreeAncestor
- java.lang.Object
-
- g1401_1500.s1483_kth_ancestor_of_a_tree_node.TreeAncestor
-
public class TreeAncestor extends Object
1483 - Kth Ancestor of a Tree Node.Hard
You are given a tree with
nnodes numbered from0ton - 1in the form of a parent arrayparentwhereparent[i]is the parent ofithnode. The root of the tree is node0. Find thekthancestor of a given node.The
kthancestor of a tree node is thekthnode in the path from that node to the root node.Implement the
TreeAncestorclass: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 thekthancestor of the given nodenode. If there is no such ancestor, return-1.
Example 1:

Input [“TreeAncestor”, “getKthAncestor”, “getKthAncestor”, “getKthAncestor”] [[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]]
Output: [null, 1, 0, -1]
Explanation:
TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);
treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3
treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5
treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor
Constraints:
1 <= k <= n <= 5 * 104parent.length == nparent[0] == -10 <= parent[i] < nfor all0 < i < n0 <= node < n- There will be at most
5 * 104queries.
-
-
Constructor Summary
Constructors Constructor Description TreeAncestor(int n, int[] parent)
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description intgetKthAncestor(int node, int k)
-