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.

// Definition for a binary tree node.
public class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) { val = x; }
}

Java Solution

The node does not have a pointer pointing to its parent. This is different from Inorder Successor in BST II.

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;
}

When the tree is balanced, time complexity is O(log(n)) and space is O(1). The worst case time complexity is O(n).

3 thoughts on “LeetCode – Inorder Successor in BST (Java)”

  1. think next as the last ancestor where u took left turn ( where your node values was less than parent value) .

  2. The above program would be must easy to understand , if “next” Node is renamed with “parent”

  3. 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;

    }

Leave a Comment