Lowest Common Ancestor of a Binary Tree

Medium · Trees · Tree · DFS · Recursion

Problem

Given a binary tree and two values p and q present in it, return the value of their lowest common ancestor — the deepest node having both as descendants. A node counts as a descendant of itself.

The tests build the tree and look the nodes up by value for you.

Examples

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

The root is the deepest node containing both.

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

5 is an ancestor of 4, and a node is its own descendant.

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…