oneby7

Binary Search Trees Using the ordering

397. Inorder Successor in BST

Medium

You are given root, the root node of a binary search tree, and one of its nodes, p. Return the in-order successor of p: the node with the smallest value greater than p.val. If no value in the tree is greater than p.val, return null.

In a binary search tree, every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. The values in the tree are distinct. The name comes from the in-order walk (left subtree, node, right subtree), which visits the values from smallest to largest. The successor is the node that walk visits right after p.

Return a node of the tree itself, not a new node with the same value. The nodes have no link to their parent.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out. p is written as the value it holds, and the output shows the value of the node you return, or null.

Example 1

2025303540455060657080

Input: root = [50, 30, 70, 20, 40, 60, 80, null, 25, 35, 45, null, 65] p = 45

Output: 50

Explanation: The values larger than 45 are 50, 60, 65, 70 and 80. The smallest of them is 50, the root, three levels above 45.

Example 2

2025303540455060657080

Input: root = [50, 30, 70, 20, 40, 60, 80, null, 25, 35, 45, null, 65] p = 30

Output: 35

Explanation: The right child of 30 is 40, but 35, the left child of 40, is smaller. No other value lies between 30 and 35.

Example 3

−10⁹010⁹

Input: root = [0, -1000000000, 1000000000], p = 1000000000

Output: null

Explanation: p holds the largest value in the tree, so no node comes after it.

Check your understanding

Work out the answer for this input before you write any code.

root = [50, 30, 70, 20, 40, 60, 80, null, 25, 35, 45, null, 65] p = 65

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.
  • The tree is a binary search tree, and its values are distinct.
  • p is a node of the tree.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.