Problem · Tree
Inorder Successor in a Binary Search Tree
Learn this problemProblem statement
You are given the root root of a non-empty binary search tree and an integer targetValue that appears in the tree.
Return the value of the node immediately after the target in an inorder traversal. An inorder traversal visits the left subtree, then the node, then the right subtree. If the target is the largest value and has no inorder successor, return -1.
The tree has no parent pointers and all node values are distinct.
Function
findInorderSuccessor(root: TreeNode, targetValue: int) → intExamples
Example 1
root = [20,10,30,5,15,25,35]targetValue = 15return = 20The inorder sequence is [5,10,15,20,25,30,35], so 20 follows 15.
Example 2
root = [20,10,30,5,15,25,35,2,7,13,17]targetValue = 10return = 13The target has a right subtree. Its successor is the leftmost value in that subtree, 13.
Example 3
root = [2,1,3]targetValue = 3return = -1The largest value is last in inorder order, so it has no successor.
Constraints
- The tree contains between
1and100000nodes. 0 <= Node.val <= 1000000000.- All node values are distinct, and the tree satisfies the binary-search-tree ordering invariant.
targetValueequals the value of exactly one node.