bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 235. Lowest Common Ancestor of a Binary Search Tree

235. Lowest Common Ancestor of a Binary Search Tree

Leetcode Solutions

Iterative Approach for Finding LCA in a BST

  1. Initialize a pointer current to the root of the BST.
  2. While current is not null: a. Compare the values of p and q with the value of current. b. If both p and q are greater than current, move current to its right child. c. If both p and q are less than current, move current to its left child. d. If the values of p and q are on opposite sides of current, or one of them equals current, then current is the LCA. Return current.
  3. If the LCA is not found in the loop (which should not happen in a valid BST with all unique values), return null.
UML Thumbnail

Recursive Approach for Finding LCA in a BST

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...