Home
Log in
DescriptionSubmissionsSolution
DescriptionSubmissionsSolution
Loading...

Log in to run or submit

root =
p =
q =

Codey

Practise coding problems, test your solutions and track your progress.

Explore

  • Problems
  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

© 2026 Codey. Personal learning project.

Solution
Updated: 2026-02-23

Idea

In a BST, if both targets are smaller, LCA is in left subtree; if both larger, in right subtree.

Approach

Iteratively walk from root:

  • If p and q are both < current, go left.
  • If both > current, go right.
  • Otherwise current is the split point (LCA).

Why it works

BST ordering guarantees the first node where paths to p and q diverge is the lowest common ancestor.

Code
Loading...
Complexity
Time: O(h)
Space: O(1)
Solution
Updated: 2026-02-23

Idea

In a BST, if both targets are smaller, LCA is in left subtree; if both larger, in right subtree.

Approach

Iteratively walk from root:

  • If p and q are both < current, go left.
  • If both > current, go right.
  • Otherwise current is the split point (LCA).

Why it works

BST ordering guarantees the first node where paths to p and q diverge is the lowest common ancestor.

Code
Loading...
Complexity
Time: O(h)
Space: O(1)