Lowest Common Ancestor of a Binary Search Tree

Medium Solved

Description

Given a Binary Search Tree (BST), find the lowest common ancestor (LCA) of two given nodes p and q.

The lowest common ancestor is defined as the lowest node in the tree that has both p and q as descendants (where a node can be a descendant of itself).

Input format / Clarification:

  • Line 1: BST as level-order array (use null for empty)
  • Line 2: Value of node p
  • Line 3: Value of node q

Example 1:

Input:
[6,2,8,0,4,7,9,null,null,3,5]
2
8

Output:
6

Example 2:

Input:
[6,2,8,0,4,7,9,null,null,3,5]
2
4

Output:
2

Note:

Your program must print only the value of the lowest common ancestor.

Your Submissions

No submissions yet.

Discuss

Discuss BST properties, iterative vs recursive approaches.

Test Cases