Back to Practice Dashboard
Top 150 InterviewEasy

Lowest Common Ancestor of BST

Learn how to solve the 'Lowest Common Ancestor of BST' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.

According to the definition of LCA: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)."

The BST is represented as a level-order list. Implement a function lowestCommonAncestor(root: list, p: int, q: int) -> int that returns the value of the LCA node.

Constraints
  • The number of nodes in the tree is in the range [2, 100000]
  • -1000000000 <= Node.val <= 1000000000
  • All Node.val are unique
  • p != q
  • p and q will exist in the BST

Examples

Example 1
Input
[6,2,8,0,4,7,9,None,None,3,5], 2, 8
Output
6
Explanation

The LCA of nodes 2 and 8 is 6, which is the root.

Example 2
Input
[6,2,8,0,4,7,9,None,None,3,5], 2, 4
Output
2
Explanation

The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself.

Example 3
Input
[2,1], 2, 1
Output
2
Explanation

The LCA of nodes 2 and 1 is 2.

Need a Hint?
Perform a recursive tree traversal (DFS) or level-order traversal (BFS) using a queue/stack.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor