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) {
        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;
            c= c.right;
        return null;
        return next;
    c = c.right;
        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).

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

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

  • Subodh Karwa

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

  • 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) {

    else {

    BinaryTreeNode temp = nodeStoreStack.pop();

    if(temp==findNode) {

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

    return successor;

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




    return null;