We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
An easy trees problem, graded against 6 test cases (3 of them hidden).
Recursive traversal of binary trees and BSTs - depth, validation, and path problems.
Reach for it when you see: A TreeNode input, or anything about depth, ancestry, or in-order ordering.
More Treesproblems →The general-tree version of this problem requires searching both subtrees and combining results. A BST makes it almost trivial, because comparing values tells you where each target lives without looking.
Descend from the root. While both targets are less than the current value, both are in the left subtree, so move left; while both are greater, move right. The first node where they diverge - one on each side, or one equal to the current node - is the lowest common ancestor, because any deeper node would have both targets on the same side of it and could not be an ancestor of both.
That "or one equals the current node" clause is what implements the rule that a node counts as its own descendant, and it is the case people miss.
Since the walk never backtracks, this needs no recursion and no stack - a simple loop in O(1) space. It runs in O(h): O(log n) on a balanced tree, O(n) on a degenerate one.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.