LeetCode[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, return null.

Iteration

复杂度
O(lgN), O(lgN)

思路
找的是比这个node大的最小值。

代码

public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
    if(root == null) return null;
    TreeNode res = null;
    while(root != null) {
        // 如果是小于等于的值,就要往右移动
        if(root.val <= p.val) {
            root = root.right;
        }
        // 比root大的值都可能是successor,所以要保留
        else {
            res = root;
            root = root.left;
        }
    }
    return res;
}

hellolittleJ17
10 声望11 粉丝