KatInterview

235. Lowest Common Ancestor of a Binary Search Tree

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the Lowest Common Ancestor (LCA) of two nodes, p and q, in a Binary Search Tree (BST). The key to solving this problem efficiently is to leverage the inherent properties of a BST:

Solution

Lowest Common Ancestor of a Binary Search Tree in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        # Start traversing from the root.
        current = root
        
        while current:
            # If both p and q have values smaller than the current node's value,
            # it means the LCA must be in the left subtree.
            if p.val < current.val and q.val < current.val:
                current = current.left
            # If both p and q have values larger than the current node's value,
            # it means the LCA must be in the right subtree.
            elif p.val > current.val and q.val > current.val:
                current = current.right
            # If the values of p and q are on opposite sides of the current node,
            # or one of them is equal to the current node, then the current node
            # is the split point, which is the LCA.
            else:
                return current
        
        # This line is unreachable given the problem constraints.
        return None

Lowest Common Ancestor of a Binary Search Tree in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        // Start traversing from the root.
        TreeNode current = root;
        
        while (current != null) {
            // If both p and q have values smaller than the current node's value,
            // it means the LCA must be in the left subtree.
            if (p.val < current.val && q.val < current.val) {
                current = current.left;
            } 
            // If both p and q have values larger than the current node's value,
            // it means the LCA must be in the right subtree.
            else if (p.val > current.val && q.val > current.val) {
                current = current.right;
            } 
            // If the values of p and q are on opposite sides of the current node,
            // or one of them is equal to the current node, then the current node
            // is the split point, which is the LCA.
            else {
                return current;
            }
        }
        
        // This part is unreachable given the problem constraints that p and q exist in the BST.
        return null;
    }
}

Lowest Common Ancestor of a Binary Search Tree in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        // Start traversing from the root.
        TreeNode* current = root;
        
        while (current != NULL) {
            // If both p and q have values smaller than the current node's value,
            // it means the LCA must be in the left subtree.
            if (p->val < current->val && q->val < current->val) {
                current = current->left;
            } 
            // If both p and q have values larger than the current node's value,
            // it means the LCA must be in the right subtree.
            else if (p->val > current->val && q->val > current->val) {
                current = current->right;
            } 
            // If the values of p and q are on opposite sides of the current node,
            // or one of them is equal to the current node, then the current node
            // is the split point, which is the LCA.
            else {
                return current;
            }
        }
        
        // This line should not be reached given the problem constraints
        // (p and q will exist in the BST).
        return NULL;
    }
};

Lowest Common Ancestor of a Binary Search Tree in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
	// The problem constraints guarantee root, p, and q are non-null.
    let current: TreeNode | null = root;

    while (current) {
        // If both p and q have values smaller than the current node's value,
        // it means the LCA must be in the left subtree.
        if (p!.val < current.val && q!.val < current.val) {
            current = current.left;
        } 
        // If both p and q have values larger than the current node's value,
        // it means the LCA must be in the right subtree.
        else if (p!.val > current.val && q!.val > current.val) {
            current = current.right;
        } 
        // If the values of p and q are on opposite sides of the current node,
        // or one of them is equal to the current node, then the current node
        // is the split point, which is the LCA.
        else {
            return current;
        }
    }

    // This part is unreachable given the problem constraints.
    return null;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.