FastPrepInorder Successor in a Binary Search Tree
Problem · Tree

Inorder Successor in a Binary Search Tree

Learn this problem
MediumCharta Health logoCharta HealthFULLTIMEONSITE INTERVIEW

Problem 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) → int

Examples

Example 1

root = [20,10,30,5,15,25,35]targetValue = 15return = 20

The 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 = 13

The target has a right subtree. Its successor is the leftmost value in that subtree, 13.

Example 3

root = [2,1,3]targetValue = 3return = -1

The largest value is last in inorder order, so it has no successor.

Constraints

  • The tree contains between 1 and 100000 nodes.
  • 0 <= Node.val <= 1000000000.
  • All node values are distinct, and the tree satisfies the binary-search-tree ordering invariant.
  • targetValue equals the value of exactly one node.

More Charta Health problems

drafts saved locally
public int findInorderSuccessor(TreeNode root, int targetValue) {
    // Write your code here.
}
root[20,10,30,5,15,25,35]
targetValue15
expected20
checking account