Algo-Sim › Binary Trees & BST

Lowest Common Ancestor of a Binary Tree

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

Each call returns p, q or the LCA from its subtree. The first node where both sides return something is the answer.

Problem

Given a binary tree and two of its nodes p and q, return their lowest common ancestor: the deepest node that has both p and q in its subtree. A node counts as part of its own subtree.

Constraints

Edge cases to test

Follow-up questions

What if the tree is a BST?
Walk down from the root: go left while both are smaller, right while both are larger: O(h) (LC 235).
What if nodes have parent pointers?
Walk both up like Intersection of Two Linked Lists: O(h), O(1).
What if p or q might be missing?
Count how many of them the search actually found and return null unless both were (LC 1644).

Solution

Java

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null || root == p || root == q) return root;
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);
    if (left != null && right != null) return root;
    return left != null ? left : right;
}

Python

def lowest_common_ancestor(root, p, q):
    if not root or root is p or root is q:
        return root
    left = lowest_common_ancestor(root.left, p, q)
    right = lowest_common_ancestor(root.right, p, q)
    if left and right:
        return root
    return left or right

C++

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

class Solution {
  public:
    TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
        if (root == nullptr || root == p || root == q)
            return root;
        TreeNode *left = lowestCommonAncestor(root->left, p, q);
        TreeNode *right = lowestCommonAncestor(root->right, p, q);
        if (left != nullptr && right != nullptr)
            return root;
        return left != nullptr ? left : right;
    }
};

More Binary Trees & BST problems