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

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def inorderSuccessor(self, root, p):
        """
        :type root: TreeNode - the actual root of the tree
        :type p: TreeNode - find the next in order successor of this node
        :rtype: TreeNode
        """
        if not root or not p:
            return None

        # case 1
        if p.right:
            p = p.right
            while p.left:
                p = p.left
            return p

        # case 2
        prev = None
        while root != p:
            if p.val > root.val:
                root = root.right
            else:
                prev = root
                root = root.left
        return prev

Last updated