Problem 38 of 75

Lowest Common Ancestor of a Binary Tree

MediumNot solved yetInterview me on this
Before you code · which pattern fits?

The problem

Given a binary tree and two nodes p and q, return their lowest common ancestor (LCA): the lowest node that has both p and q as descendants (a node can be a descendant of itself).

([3,5,1,6,2,0,8,null,null,7,4], p=5, q=1) → 3 (…, p=5, q=4) → 5

Your solution runs against 2 unit tests, including edge and large-value cases.

Loading...

Test console · 2 unit tests

Submit your code to run it against all 2 unit tests. Results appear here.

JavaScript, TypeScript & Python run sandboxed in your browser; other languages run on the execution server. Your code is saved locally as you type.

Hint

Reference solution

Video explanation

Lowest Common Ancestor of a Binary Tree, explainedCracking FAANG