23 · Binary Search Trees

#235 Lowest Common Ancestor of a Binary Search Tree

Mediumsolve on LeetCode ↗

frequently reported atLinkedInMetaBloombergAmazonMicrosoftGoogle

the problem

In plain words

Given a BST and two different nodes p and q in it, return their lowest common ancestor (a node may be its own ancestor).

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

out 6

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

out 2

  • 2 ≤ number of nodes ≤ 10⁵
  • -10⁹ ≤ Node.val ≤ 10⁹
  • Values unique, p ≠ q, both 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. #236
    2. #700
    3. #285
      Inorder Successor in BST
      Mediumin BSTLeetCode Premium