Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Inorder Successor in BST

Medium Acceptance 60.12% Points 30.00

You are given the root of a Binary Search Tree (BST) and a target node. Your task is to find its inorder successor.

The inorder successor of a node is the node with the smallest value greater than the target's value.

If no such node exists, return null.

Examples
Example 1

image Input: root = [5,3,8,1,4,null,9], target = 4
Output: 5
Explanation: In inorder traversal (1, 3, 4, 5, 8, 9), the value that immediately follows 4 is 5.

Example 2

image Input: root = [5,3,8,1,4,null,9], target = 9
Output: null
Explanation: 9 is the largest value in the BST, so it has no inorder successor.

Example 3

image Input: root = [2,1,3], target = 1
Output: 2
Explanation: The inorder sequence is 1, 2, 3, so the successor of 1 is 2.

Hints
Hint 1
In an inorder traversal of a BST:
Hint 2
  • Nodes are visited in ascending order.
Hint 3
  • The inorder successor is the value that appears immediately after the target value.
Constraints
    • 1 = Number of nodes = 104
    • -10? = Node.data = 10?
    • All node values are unique
Companies
Paytm Sprinklr Media.net
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions