4
List<Integer>[] nodeInPath;7
public TreeAncestor(int n, int[] parent) {10
nodeInPath = new ArrayList[n];11
nodeIdxInPath = new int[n];16
boolean[] inner = new boolean[n];17
for (int i = 1; i < n; i++) {18
inner[parent[i]] = true;21
for (int i = 1; i < n; i++) {22
if (inner[i] || nodeInPath[i] != null) {25
List<Integer> path = new ArrayList<>();32
for (int j = 0; j < m; j++) {33
int node = path.get(j);34
if (nodeInPath[node] != null) break;35
nodeInPath[node] = path;36
nodeIdxInPath[node] = j;41
public int getKthAncestor(int node, int k) {42
List<Integer> path = nodeInPath[node];43
int idx = nodeIdxInPath[node] + k;44
return idx >= path.size() ? -1 : path.get(idx);