15% off all plans & roadmaps Use code
See plansLeetCode 236 · Solution & editorial
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
Lowest Common Ancestor of a Binary Tree is a Tree Traversal Patterns (DFS & BFS) problem, in the Lowest Common Ancestor (LCA) Finding subpattern. The pattern covers preorder, inorder, level order traversal, LCA, and serialization
Find lowest common ancestor in binary trees and BSTs using recursive and iterative approaches.
The reference solution runs in O(N) time and O(N) space.
Lowest Common Ancestor of a Binary Tree has been reported in interviews at Facebook, Microsoft, Amazon, Oracle, LinkedIn, Apple, Bloomberg, Intuit.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Lowest Common Ancestor of a Binary Tree is a Tree Traversal Patterns (DFS & BFS) problem, in the Lowest Common Ancestor (LCA) Finding subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.