LeetCode #285 Medium

Inorder Successor in BST

Inorder Successor in BST is LeetCode 285 (Medium). Given the root of a binary search tree and a node p in it, return the node that comes right after p in an inorder traversal.

  • Inorder order of a BST is sorted order, so this is the node with the smallest value greater than p.val.
  • Return null if p holds the largest value.

Nodes have no parent pointers, and the tree may hold up to 10⁴ nodes with unique values.

Constraints
  • The number of nodes in the tree is in the range [1, 10⁴].
  • -10⁵ <= Node.val <= 10⁵
  • All Nodes will have unique values.
  • p is a node in the tree.
bstbinary-search
Open on LeetCode ↗
02

Intuition

Walk down from the root and compare each node with p.val. A node larger than p.val is a possible answer, so save it and go left to look for a smaller one that still beats p. A node that is not larger cannot be the answer, and neither can anything in its left subtree, so go right.

Each saved node is smaller than the one saved before it, because it was found in that node's left subtree. Every node the walk skips was ruled out by one comparison. So when the cursor falls off the tree, the last saved node is the smallest value above p.val.

How to spot this pattern

Successor, predecessor, floor and ceil in a BST are all one walk down from the root that keeps the best node seen so far. Only the comparison and the direction of the turn change between them.

03

Approach

Try it first

Before reading on, take the tree [20, 8, 22, 4, 12, null, null, null, null, 10, 14]. Find the successor of 8, then of 14. Which one sits in p's right subtree and which one is an ancestor? Aim for O(h) time and O(1) space.

1

Start at the root with no answer

Set succ = None and point node at the root. Starting from the top, rather than from p, is what removes the need for parent pointers: every ancestor of p lies on the way down.

2

Larger than p: save it and go left

If node.val > p.val, this node could be the successor, so set succ = node. A closer answer would be smaller than node.val, and in a BST those values are in the left subtree, so move to node.left.

3

Not larger than p: go right

If node.val <= p.val, this node is too small, and so is its whole left subtree. The only values that could still beat p are to the right, so move to node.right. The <= sends p itself to the right as well, since the answer must be strictly greater.

4

Return the last saved node

When node becomes None, return succ. If nothing on the path was larger than p, succ is still None, which is correct: p holds the largest value in the tree.

5

Why one loop covers both textbook cases

If p has a right subtree, the walk reaches p, turns right and then keeps going left, ending at the leftmost node of that subtree. If it has none, the walk falls off just below p, and succ holds the last ancestor where it turned left. Both answers come out of the same loop.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def inorderSuccessor(self, root, p):
▶3 succ = None
▶4 node = root
▶5 while node:
▶6 if node.val > p.val:
▶7 succ = node
▶8 node = node.left
▶9 else:
▶10 node = node.right
▶11 return succ
48p1012142022succnoneno answer yet, start at the root 20
p.val8
succNonenothing larger seen yet
The successor is the smallest value greater than 8. Start at the root with no candidate. Only p.val is needed, so the walk never has to locate p first or climb back up through parents.
48p1012142022succ2020 > 8 → save, go left
node20greater than p
succ20best so far
20 is greater than 8, so it could be the successor: save it. A closer answer can only be smaller than 20, and those values live in its left subtree, so go left.
48p1012142022succ208 = p → go right
node8this is p
succ20unchanged
This is p itself. It is not greater than 8, so it cannot be the answer. Anything larger must be to the right, so go right.
48p1012142022succ20>1212 > 8 → save, go left
node12greater than p
succ12best so far
12 is greater than 8, so it could be the successor: save it, replacing 20, which is larger. A closer answer can only be smaller than 12, and those values live in its left subtree, so go left.
48p1012142022succ20>12>1010 > 8 → save, go left
node10greater than p
succ10best so far
10 is greater than 8, so it could be the successor: save it, replacing 12, which is larger. A closer answer can only be smaller than 10, and those values live in its left subtree, so go left. There is no left child, so the walk ends.
48p1012142022succ20>12>10fell off the tree → answer 10
returnnode 10
Each saved value was smaller than the one before it, and every node left out of the walk was ruled out by one comparison. So 10, the last value saved, is the smallest value greater than 8.
05

Common pitfalls

Returning the first node larger than p

✗ Wrong
if node.val > p.val:
    return node
✓ Right
if node.val > p.val:
    succ = node
    node = node.left

The first larger node met on the way down is often not the closest. In [20, 8, 22, 4, 12, null, null, null, null, 10, 14] with p = 8, the root 20 is larger than 8 and is returned, but the answer is 10.

Looking only in p's right subtree

✗ Wrong
node = p.right
while node.left:
    node = node.left
return node
✓ Right
start at the root and run the save-and-go-left walk

This only works when p has a right child. In the same tree with p = 14, p.right is null, so the code crashes on node.left; the real answer is the ancestor 20.

Comparing with >= instead of >

✗ Wrong
if node.val >= p.val:
✓ Right
if node.val > p.val:

With >=, the walk saves p itself when it reaches it. For p = 14 in the same tree, succ ends as node 14 instead of 20, because nothing on the path after p replaces it.

06

Edge cases

p holds the largest value

Every node on the path is at most p.val, so the walk only goes right, nothing is saved, and the result is None.

A one-node tree

The root is p. It is not larger than itself, so the walk goes right, falls off, and returns None.

A tree that is one long chain

The walk is still correct but visits up to all 10⁴ nodes, since the height equals the number of nodes. The loop uses no recursion, so depth is not a problem.

07

Complexity

Time
O(h)
Space
O(1)
h is the height of the tree. The cursor moves down one level per step and never comes back up, so it visits at most h + 1 nodes: about log₂ n in a balanced tree and n in a chain. Only node and succ are stored.
08

Inorder Successor in BST FAQ

Why not do an inorder traversal and take the node after p?

It is correct but visits up to every node and, if you collect the values, stores all n of them: O(n) time and O(n) space. The BST ordering already says which way the answer lies at each node, so one path of length h is enough.

How is this different from Inorder Successor in BST II?

In problem 510 you get only the node p, and each node has a parent pointer but you get no root. There you take the leftmost node of p.right if it exists; otherwise you climb parents until you arrive from a left child. Here there are no parent pointers, so you walk down from the root instead.

How do you find the inorder predecessor instead?

Mirror every choice: save a node when node.val < p.val and go right to look for a larger one, otherwise go left. The last saved node is the largest value smaller than p.val.