Chaturmind
LearnDSASystem DesignBlogPremium
Sign inGet started
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML

Company

  • Blog
  • Premium
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.

DSA›Trees›Lowest Common Ancestor of a Binary Tree
MediumTrees

Lowest Common Ancestor of a Binary Tree

treerecursionlca

Problem

Given a binary tree and two nodes p and q, find their lowest common ancestor (the deepest node that has both p and q as descendants, where a node can be a descendant of itself).

Examples

Example 1

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1

Output: 3

Explanation: 5 and 1 are direct children of 3, so 3 is their LCA.

Constraints

  • •The number of nodes is in the range [2, 10^5]
  • •p and q both exist in the tree and are distinct

Hints

Hint 1

A recursive search naturally answers 'does this subtree contain p or q (or both)?' — build the LCA logic on top of that.

Hint 2

If a node's left subtree contains one target and its right subtree contains the other, that node itself IS the LCA — think about why.

Hint 3

If a subtree search returns one of the targets directly, that's also a valid signal to propagate upward — the found node could itself be an ancestor of the other target higher up.

Solutions

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; // p and q found in DIFFERENT subtrees — root is the split point, hence the LCA
    return left != null ? left : right; // both targets (or the only one found so far) are on one side — propagate that up
}
Java

Time: O(n) · Space: O(h)