Back to DSA

Lowest Common Ancestor of a Binary Tree

medium
Acceptance: 53%
Binary Tree

In a binary tree (not necessarily a BST), find the lowest common ancestor of two specified nodes. The lowest common ancestor is the deepest node that is an ancestor of both target nodes. A node is considered an ancestor of itself.

Examples

Example 1:
Input:root = [10,5,15,3,7,12,20], p = 3, q = 7
Output:5
Example 2:
Input:root = [10,5,15,3,7,12,20], p = 5, q = 20
Output:10

Hints

00:00
1234567