Lowest Common Ancestor of a Binary Tree

Medium

Company Tags

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

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Example 1:

Input: root = [5,3,4,2,1], p = 1, q = 2

Output: 3

Example 2:

Input: root = [5,3,4,2,1,null,9,null,11,10,12], p = 3, q = 12

Output: 3

Constraints:

  • 2 <= The number of nodes in the tree <= 100,000.
  • -1,000,000,000 <= Node.val <= 1,000,000,000
  • All Node.val are unique.
  • p != q
  • p and q will both exist in the tree.


Company Tags

Please upgrade to NeetCode Pro to view company tags.

root =

p =

q =