Skip to main content

Lowest Common Ancestor of a Binary Tree

MediumPremium

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

The lowest common ancestor is defined between two nodes p and q as the lowest node in the tree that has both p and q as descendants (where we allow a node to be a descendant of itself).

Example

Consider the following binary tree:

Tree: 10 / \ 5 15 / \ \ 3 7 20 / \ / 1 8 17
  • The lowest common ancestor of nodes 5 and 15 is node 10.
  • The lowest common ancestor of nodes 3 and 7 is node 5.