285 Inorder Successor in BST

285. Inorder Successor in BST

1. Question

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.

2. Implementation

(1) Inorder traversal

class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (root == null) {
            return null;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode curNode = root, preNode = null;

        while (curNode != null || !stack.isEmpty()) {
            if (curNode != null) {
                stack.push(curNode);
                curNode = curNode.left;
            }
            else {
                curNode = stack.pop();
                if (preNode != null && preNode == p) {
                    return curNode;
                }
                preNode = curNode;
                curNode = curNode.right;
            }
        }
        return null;
    }
}

(2) Binary Search

思路: 利用Binary Search Tree的二分特性

class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (root == null) {
            return null;
        }

        TreeNode curNode = root;
        TreeNode successor = null;

        while (curNode != null) {
            if (curNode.val <= p.val) {
                curNode = curNode.right;
            }
            else {
                successor = curNode;
                curNode = curNode.left;
            }
        }
        return successor;
    }
}

3. Time & Space Complexity

Inorder Traversal: 时间复杂度: O(n), 空间复杂度: O(h)

Binary Search: 时间复杂度: O(logn), 空间复杂度: O(1)

Last updated