Back to DSA

Lowest Common Ancestor of a BST

medium
Acceptance: 51%
BST

Given a binary search tree and two node values, find their lowest common ancestor. Because the tree obeys BST ordering, you can determine whether both targets lie in the left subtree, the right subtree, or are split across the current node.

Examples

Example 1:
Input:root = [10,4,16,2,8,12,20], p = 2, q = 8
Output:4
Example 2:
Input:root = [10,4,16,2,8,12,20], p = 4, q = 16
Output:10

Hints

00:00
1234567