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
- 1 ≤ k ≤ n ≤ 5 · 10⁴
- parent[0] = −1 and 0 ≤ parent[i] < n for i ≥ 1
- The parents form a valid tree
- Up to 5 · 10⁴ queries
Edge cases to test
- k larger than the node’s depth (−1)
- Querying the root
- A single long chain
- k exactly equal to the depth (the root)
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 nodeC++
#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
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Zigzag Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Vertical Order Traversal of a Binary Tree (Hard)
- Maximum Depth of Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum II (Medium)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- All Nodes Distance K in Binary Tree (Medium)
- Validate Binary Search Tree (Medium)
- Search in a Binary Search Tree (Easy)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Kth Smallest Element in a BST (Medium)
- Binary Search Tree Iterator (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- AVL Tree Insert (Hard)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Binary Tree Maximum Path Sum (Hard)
- Serialize and Deserialize Binary Tree (Hard)