15% off all plans & roadmaps Use code
See plansLeetCode 235 · Solution & editorial
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
Lowest Common Ancestor of a Binary Search 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(h) time and O(n) space.
Lowest Common Ancestor of a Binary Search Tree has been reported in interviews at Amazon, Facebook, LinkedIn, Oracle, Microsoft.
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 Search 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.