Data Structures · Visualization
BST: In-order Successor
Binary Search Tree
The in-order successor of a node is the next larger value in the tree's sorted order. Time: O(h) where h is tree height. Space: O(1) iterative.
Big-O: Search/insert/delete O(log n) on a balanced tree, O(n) worst case.
BST: In-order Successor
Binary Search TreeThe in-order successor of a node is the next larger value in the tree's sorted order. If the node has a right subtree, the successor is that subtree's leftmost node; otherwise it's the nearest ancestor for which the node lies in the left subtree.
How In-order Successor Works
- If the target node has a right child, go right once, then keep going left until there's no left child — that's the successor.
- If the target node has no right child, walk down from the root toward the target, remembering the last node where you turned left.
- That last 'turned left at' node is the successor.
- If no such ancestor exists, the target node is the largest value and has no successor.
In-order Successor Worked Example
Input: Find the in-order successor of 8 in a BST with root 10, left subtree containing 8 (with right child 9)
- Node 8 has a right child (9)
- Go right to 9, then check for a left child of 9 — none exists
- 9 has no left child, so 9 itself is the successor
Output: In-order successor of 8 is 9
Press ▶ Run to watch it step by step.
def insert(root, val):
if not root:
return Node(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
# O(log n) on a balanced tree
# example: successorBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
In-order Successor Time & Space Complexity
When to Use In-order Successor
- Implementing iterative in-order traversal without recursion
- Range / next-key queries in ordered maps
- Database index cursor 'next record' operations
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.