861885. Kth common ancestor in BST

Medium

Here is a detailed Markdown blog post for the GeeksforGeeks problem "Kth common ancestor in BST":

Kth common ancestor in BST

Summary

Given a binary search tree (BST) and two nodes in the tree, find the kth common ancestor of these two nodes. The kth common ancestor is defined as the node that is at a distance of k from both nodes.

This problem involves traversing the tree and finding the common ancestors between the two given nodes.

Detailed Explanation

To solve this problem, we will use a recursive approach to traverse the BST and find the kth common ancestor. Here's a step-by-step breakdown:

  1. Start at the root of the BST.
  2. If the current node is one of the given nodes, return it as the answer (since it's the closest ancestor).
  3. If the current node is not one of the given nodes, recursively traverse the left subtree if the current node is less than both given nodes, or the right subtree if the current node is greater than both given nodes.
  4. Keep track of the distance from each node to the current node. When we find a common ancestor at a distance of k from both nodes, return it as the answer.

Here's an ASCII art diagram of the BST:

       8
     /   \
    3      10
   / \    /   \
  1   6 9     14

Time complexity: O(n), where n is the number of nodes in the BST. We visit each node once.

Space complexity: O(h), where h is the height of the BST. This is because we need to store the recursive call stack, which can be as high as the height of the tree.

Optimized Solutions

Java

View on GeeksforGeeks
class Node {
    int val;
    Node left, right;

    public Node(int val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

public class KthCommonAncestor {
    public static Node kthCommonAncestor(Node root, Node p, Node q, int k) {
        if (p.val == q.val) return p;

        boolean isPLeft = isLeft(root, p);
        boolean isQLeft = isLeft(root, q);

        if (isPLeft && isQLeft) return kthCommonAncestor(root.left, p, q, k - 1);
        if (!isPLeft && !isQLeft) return kthCommonAncestor(root.right, p, q, k - 1);

        return root;
    }

    public static boolean isLeft(Node root, Node node) {
        while (root != null) {
            if (node.val == root.val) return false;
            if (node.val < root.val) root = root.left;
            else root = root.right;
        }
        return false;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.