Category: Binary Search Tree

Inorder Successor in BST

public TreeNode inorderSuccessor(TreeNode root, TreeNode target) {
    if(root == null){
        return root;
    }
    TreeNode parent = null;
    TreeNode cur = root;
    while(cur != null && cur.val != target.val){
        if(cur.val > target.val){
            parent = cur;
            cur = cur.left;
        } else {
            cur = cur.right;
        }
    }
    if(cur == null){
        return null;
    }
    if(cur.right == null){
        return parent;
    }
    cur = cur.right;
    while(cur.left != null){
        cur = cur.left;
    }
    return cur;
}

 inorder-successor-in-bst