Inorder Successor in Binary Search Tree

update Aug 28, 2017 17:50

LintCodearrow-up-right LeetCodearrow-up-right

Given a binary search tree (See Definition) and a node in it, find the in-order successor of that node in the BST.

If the given node has no in-order successor in the tree, return null.

Notice

It's guaranteed p is one node in the given tree. (You can directly compare the memory address to find p)

Example

    Given tree = [2,1] and node = 1:

              2
             /
            1
    return node 2.

    Given tree = [2,1,3] and node = 2:

              2
             / \
            1   3
    return node 3.

Challenge

O(h), where h is the height of the BST.

Basic Idea:

根据CLRS(算法导论)中的思想,找一个节点 p 的 successor 的最快方法如下:

  • 如果 p 有右子树,则 successor 为其右子树中最小的元素,即 p.right.leftMost

  • 如果 p 没有右子树,则向 parent 方向一路向上看,successor 就是第一个右祖先,即p所在子树是其左子树;

这个算法的时间复杂度是 O(h);

Java Code:

Python Code: