Inorder Successor in BST | Practice | GeeksforGeeks

Given a BST, and a reference to a Node x in the BST. Find the Inorder Successor of the given node in the BST.
 
Example 1:
Input:
      2
    /   \
   1     3
K(data of x) = 2
Output: 3 
Explanation: 
Inorder traversal : 1 2 3 
Hence, inorder successor of 2 is 3.


Example 2:
Input:
             20
            /   \
           8     22
          / \
         4   12
            /  \
           10   14
K(data of x) = 8
Output: 10
Explanation:
Inorder traversal: 4 8 10 12 14 20 22
Hence, successor of 8 is 10.
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function inOrderSuccessor(). This function takes the root node and the reference node as argument and returns the node that is inOrder successor of the reference node. If there is no successor, return null value.

Expected Time Complexity: O(Height of the BST).
Expected Auxiliary Space: O(1).

Constraints:
1 <= N <= 1000, where N is number of nodes
0
utkarsh061 day ago
Node * inOrderSuccessor(Node *root, Node *x)
    {
        Node* successor = NULL;
        
        while(root != NULL)
        {
            if(root->data <= x->data)
              root = root->right;
            else
            {  successor = root; //might be a possible answer
               root = root->left;
            }
        }
        return successor;
    }
0
generalandy29973 days ago
We can use Morris traversal to solve this problem, which is based on threaded binary tree.
The time complexity is O(K), where x is Kth small number in BST.
And the space complexity is O(1).
def inorderSuccessor(self, root, x):
		isSuccessor = False
       	while root:
            if root.left:
            	# If left subtree exists, we have to create right threaded
                remember = root
                child = root.left
                # Find rightmost child in left subtree
                while child.right:
                    child = child.right
                child.right = remember
                root = remember.left
                # Must remove left link or there will exist cycle
                remember.left = None
            else:
            	# we only use right link to traversal
                if isSuccessor: return root
                if root.data == x.data:
                    isSuccessor = True
                root = root.right
        return None
0
siddharthraja98496 days ago
class Solution{
  public:
    // returns the inorder successor of the Node x in BST (rooted at 'root')
    Node * inOrderSuccessor(Node *root, Node *x)
    {
        Node *ans=NULL;
        
        while(root!=NULL){
            if(root->data==x->data)
                break;
            if(root->data>x->data){
                ans=root;
                root=root->left;
            }
            else{
                root=root->right;
            }
        }
        
        if(root->right==NULL)
        {
            return ans;
        }
        Node * p=root->right;
        while(p->left!=NULL)p=p->left;
        return p;
        //Your code here
    }
};
0
tanashah1 week ago
void inorder(Node* root,queue<Node*>&q){       if(root==NULL){           return;       }       inorder(root->left,q);       q.push(root);       inorder(root->right,q);   }   Node * inOrderSuccessor(Node *root, Node *x)   {       //Your code here       if(root==NULL){           return NULL;       }              queue<Node*>q;       int temp;       inorder(root,q);       while(q.front()!=x){           q.pop();//je equal nahi te kadle       }       q.pop();       if(q.size()==0){           return NULL;       }       return q.front();   }
0
aryankhatana352 weeks ago
C++ sol
 void inorder(Node *root, vector<Node*>&a){       if(root==NULL){           return;       }https://practice.geeksforgeeks.org/problems/inorder-successor-in-bst/1/?page=1&difficulty[]=-2&difficulty[]=-1&difficulty[]=0&status[]=solved&status[]=unsolved&category[]=Binary%20Search%20Tree&sortBy=submissions#       inorder(root->left,a);       a.push_back(root);       inorder(root->right,a);          } public:   // returns the inorder successor of the Node x in BST (rooted at 'root')   Node * inOrderSuccessor(Node *root, Node *x)   {       //Your code here       vector<Node*>ans;       inorder(root,ans);       for(int i=0;i<ans.size();i++){           if(ans[i]==x && i<ans.size()-1){               return ans[i+1];           }       }       return NULL;          }
+1
smeetgadhiya012 weeks ago
 SIMPLE JAVA SOLUTION
TC : O(Height of Tree)
SC : O(1)
 
public Node inorderSuccessor(Node root,Node x)        {            Node successor = null;            while(root != null){                if(x.data >= root.data){                    root = root.right;                }else{                    successor = root;                    root = root.left;                }            }            return successor;                   }
+1
amishasahu3283 weeks ago
Node * inOrderSuccessor(Node *root, Node *x)
    {
        //Your code here
        Node *successor = NULL;
        while(root)
        {
            if(root->data <= x->data)
                root = root->right;
            else
            {
                successor = root;
                root = root->left;
            }
        }
        return successor;
    }
0
ashutoshmulky73 weeks ago
//MY accepted Java solution
class Solution
{
   // returns the inorder successor of the Node x in BST (rooted at 'root')
public Node inorderSuccessor(Node root,Node x)
        {
         if(x.right!=null){
             Node temp = x.right;
             while(temp.left!=null){
                 temp = temp.left;
             }
             return temp;
         }
         
         Node temp = root;
         Node succ = null;
         while(temp!=null){
             if(temp.data>x.data){
                 succ=temp;
                 temp=temp.left;
             }
             else if(temp.data<x.data){
                 temp=temp.right;
             }
               else{
                   break;
               }
         }
         return succ;
        }
}
0
jaatgfg111 month ago
    void inorder(Node* root,queue<Node*>&s){       if(root==NULL){           return;       }       inorder(root->left,s);       s.push(root);       inorder(root->right,s);   }   Node * inOrderSuccessor(Node *root, Node *x){       queue<Node*>s;       inorder(root,s);       while(s.front()!=x){           s.pop();                  }       s.pop();       if(s.size()==0){           return NULL;       }       return s.front();   }
+2
rajatgupta96961 month ago
 Node * inOrderSuccessor(Node *root, Node *x)   {      Node * successor=NULL;      while(root!=NULL)      {          if(root->data > x->data)          {              successor=root;               root=root->left;          }           else if(root->data <= x->data)           {               root=root->right;           }      }      return successor;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.