23 · Binary Search Trees

#285 Inorder Successor in BST

frequently reported atMicrosoftMetaGoogleAmazon

the problem

In plain words

You get the root of a BST with distinct values and a node p that lives in it. Return the node that comes right after p when the tree is read in sorted (inorder) order — that is, the node with the smallest value bigger than p.val. If p holds the largest value, return null.

in root = [20,10,30,5,15], p = 10

out 15

10 has a right subtree; its smallest value, 15, comes next.

in root = [20,10,30,5,15], p = 15

out 20

15 has no right subtree; the next value is the ancestor where the path to 15 last turned left.

in root = [20,10,30,5,15], p = 30

out null

30 is the largest value.

  • 1 ≤ number of nodes ≤ 10⁴
  • -10⁵ ≤ Node.val ≤ 10⁵
  • All values are distinct
  • p is a node of the tree

your turn

Try it before you peek

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

This one is LeetCode Premium. You don't need a subscription: solve it right here. The free alternative linked above is the closest free practice; its label says how close it is.

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. #173
    2. #450
    3. #700