Skip to main content

BST Successor Search

Hard

In a Binary Search Tree (BST), an Inorder Successor of a node is defined as the node with the smallest key greater than the key of the input node (see examples below). Given a node inputNode in a BST, you’re asked to write a function findInOrderSuccessor that returns the Inorder Successor of inputNode. If inputNode has no Inorder Successor, return null.

Explain your solution and analyze its time and space complexities.

In this diagram, the inorder successor of 9 is 11 and the inorder successor of 14 is 20.

img_02

Example:

In the diagram above, for inputNode whose key = 11

Your function would return:

The inorder successor node whose key = 12

Need a refresher on Binary Search Trees? Check out Exponent's lesson on Trees and take this interactive BST visualizer out for a spin.

Look again at the examples above (both the diagram and the text below.) Can you discern the two different cases in which a node is an Inorder Successor of a given input node?

Did you start by searching the root and traversing the tree in a binary search manner? While this works, see if you can come up with a solution that doesn't require the root.