285 Inorder Successor in BST
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, returnnull
.
The Idea: The problem can be summed up into two cases. In the first case when p
has a right child, then the next in order successor is the smallest value of that right subtree. Otherwise, we have to ascend down from the root of the tree and find p
using plain old binary search. In this case, maintain a previous node that follows root.left
, since this will be the the first largest node that is larger than root once p
is found.
Complexity: O(logn) time and O(1) space
Last updated