Algo-Sim › Binary Trees & BST

Kth Ancestor of a Tree Node

Hard · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Binary lifting: precompute the ancestor 2^j steps up for every node, then answer any k by jumping once per set bit of k.

Problem

A tree has nodes 0 to n − 1, given as a parent array where parent[i] is the parent of node i and node 0 is the root (parent[0] = −1). Build a TreeAncestor class whose getKthAncestor(node, k) returns the node k steps above node, or −1 if there is no such ancestor. Many queries are asked, so each should be fast.

Constraints

Edge cases to test

Follow-up questions

How does this give the lowest common ancestor?
Lift the deeper node until both have the same depth, then for j from high to low, jump both while up[j][a] ≠ up[j][b]. Their parent is the LCA: O(log n) per query.
Why does the order of building matter?
Row j reads only row j − 1, so fill row by row. Node numbers need not be in parent-first order.
Can you use less memory?
Store each node’s depth and answer offline with one DFS and a path stack (O(n + q)), or use long-path / ladder decomposition for O(1) per query.

Solution

Java

class TreeAncestor {
    private final int levels;
    private final int[][] up;

    public TreeAncestor(int n, int[] parent) {
        levels = 32 - Integer.numberOfLeadingZeros(n);
        up = new int[levels][];
        up[0] = parent.clone();
        for (int j = 1; j < levels; j++) {
            up[j] = new int[n];
            for (int v = 0; v < n; v++) {
                int mid = up[j - 1][v];
                up[j][v] = mid == -1 ? -1 : up[j - 1][mid];
            }
        }
    }

    public int getKthAncestor(int node, int k) {
        for (int j = 0; j < levels && node != -1; j++) {
            if ((k >> j & 1) == 1) node = up[j][node];
        }
        return node;
    }
}

Python

class TreeAncestor:
    def __init__(self, n, parent):
        self.levels = n.bit_length()
        self.up = [parent[:]]
        for j in range(1, self.levels):
            prev = self.up[j - 1]
            row = []
            for v in range(n):
                mid = prev[v]
                row.append(-1 if mid == -1 else prev[mid])
            self.up.append(row)

    def getKthAncestor(self, node, k):
        for j in range(self.levels):
            if node == -1:
                break
            if k >> j & 1:
                node = self.up[j][node]
        return node

C++

#include <bits/stdc++.h>
using namespace std;

class TreeAncestor {
    int levels;
    vector<vector<int>> up;

public:
    TreeAncestor(int n, vector<int>& parent) {
        levels = 32 - __builtin_clz(n);
        up.assign(levels, vector<int>(n));
        up[0] = parent;
        for (int j = 1; j < levels; j++) {
            for (int v = 0; v < n; v++) {
                int mid = up[j - 1][v];
                up[j][v] = mid == -1 ? -1 : up[j - 1][mid];
            }
        }
    }

    int getKthAncestor(int node, int k) {
        for (int j = 0; j < levels && node != -1; j++) {
            if (k >> j & 1) node = up[j][node];
        }
        return node;
    }
};

More Binary Trees & BST problems