22 · Tree Recursion

#236 Lowest Common Ancestor of a Binary Tree

Mediumsolve on LeetCode ↗

frequently reported atMetaAtlassianAmazonAdobeLinkedInApple

the problem

In plain words

Given two different nodes p and q that are both in the tree, return their lowest common ancestor: the deepest node that has both p and q as descendants (a node counts as a descendant of itself).

in root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1

out 3

in root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4

out 5

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

in root = [1,2], p = 1, q = 2

out 1

  • 2 ≤ number of nodes ≤ 10⁵
  • -10⁹ ≤ Node.val ≤ 10⁹
  • All values unique
  • p ≠ q, both exist in the tree

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #235
    2. #863
    3. #104
      Maximum Depth of Binary Tree
      Easyin Tree Recursion