Lowest Common Ancestor of a Binary Search Tree

Medium · Trees · Tree · Depth-First Search · Binary Search Tree · Binary Tree

Problem

Given a binary search tree and two different values p and q that are both in it, return their lowest common ancestor: the deepest node that has both of them in its subtree. A node counts as part of its own subtree, so when p is an ancestor of q, the answer is p itself.

The search-tree order does all the work. While p and q are both smaller than the current node, both are in its left subtree; while both are larger, both are in its right subtree. The first node where they split — one on each side, or one of them equal to the node — is the answer, and nothing off that one path ever needs to be looked at.

Your lowestCommonAncestor receives the root and the two nodes, and returns a node. The tests call it through a helper that builds the tree from its level-order list, finds the nodes holding p and q, and reports the value of the node you return:

Trees here are at most 500 levels deep.

Examples

Input: root = [6,2,8,0,4,7,9,None,None,3,5], p = 2, q = 8
Output: 6

2 is smaller than 6 and 8 is larger, so they split right at the root.

Input: root = [6,2,8,0,4,7,9,None,None,3,5], p = 2, q = 4
Output: 2

Both are smaller than 6, so go left to 2. That node is p itself, and 4 is below it, so 2 is the answer.

Constraints

Approaches

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…