LeetCode – Inorder Successor in BST (Java)

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

Java Solution 1

public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
    Stack<TreeNode> stack = new Stack<TreeNode>();
    if(root==null || p==null)
        return null;
 
    stack.push(root);
    boolean isNext = false;
    while(!stack.isEmpty()){
        TreeNode top = stack.pop();
 
        if(top.right==null&&top.left==null){
            if(isNext){
                return top;
            }
 
            if(p.val==top.val){
                isNext = true;
            }
            continue;
        }
 
        if(top.right!=null){
            stack.push(top.right);
            top.right=null;
        }
 
        stack.push(top);
 
        if(top.left!=null){
            stack.push(top.left);
            top.left=null;
        }
    }
 
    return null;
}

Time is O(n), Space is O(n).

Java Solution 2

public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
    if(root==null)
        return null;
 
    TreeNode next = null;
    TreeNode c = root;
    while(c!=null && c.val!=p.val){
        if(c.val > p.val){
            next = c;
            c = c.left;
        }else{
            c= c.right;
        }
    }
 
    if(c==null)        
        return null;
 
    if(c.right==null)
        return next;
 
    c = c.right;
    while(c.left!=null)
        c = c.left;
 
    return c;
}

Time is O(log(n)) and space is O(1).

Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Udaydeep Thota

    Simple and easy to understand:

    // Just do pre order traversal and while processing the node, if it is find node :
    // case 1: if node has right link, go to the left most of the right link and return the data
    // case 2: else pop the stack and return it (which means the next highest value of the node)
    // Time complexity : O(n)
    public static BinaryTreeNode findInOrderSuccessor(BinaryTreeNode root, BinaryTreeNode findNode) {

    if(root==null || findNode==null)
    return null;

    Stack nodeStoreStack = new Stack();
    BinaryTreeNode current = root;

    while (!nodeStoreStack.isEmpty() || current!=null) {

    if(current!=null) {
    nodeStoreStack.add(current);
    current=current.llink;
    }

    else {

    BinaryTreeNode temp = nodeStoreStack.pop();
    current=temp.rlink;

    if(temp==findNode) {

    if(temp.rlink!=null) {
    BinaryTreeNode successor = temp.rlink;
    while(successor.llink!=null) {

    successor=successor.llink;
    }
    return successor;

    }
    else if(!nodeStoreStack.isEmpty()) {
    return nodeStoreStack.pop();
    }

    }

    }

    }

    return null;

    }