Inorder Traversal (Iterative) | Practice | GeeksforGeeks

Given a binary tree. Find the inorder traversal of the tree without using recursion.
Example 1
Input:
           1
         /    \
       2       3
      /   \
    4     5
Output: 4 2 5 1 3
Explanation:
Inorder traversal (Left->Root->Right) of 
the tree is 4 2 5 1 3.

Example 2
Input:
            8
          /   \
            1      5
             \    /  \
             7   10   6
             \  /
          10 6
Output: 1 7 10 8 6 10 5 6
Explanation:
Inorder traversal (Left->Root->Right) 
of the tree is 1 7 10 8 6 10 5 6.
 

Expected time complexity: O(N)
Expected auxiliary space: O(N)
0
utkarshagarwal1012 weeks ago
    Node* getRightMost(Node* curr, Node* left){
        while(left->right!=NULL&&left->right!=curr){   // helper function // until left->right is NULL or equal to curr
            left=left->right;
        }
        return left;
    }
    vector<int> inOrder(Node* root)
    {
        //code here
        vector<int>ans;
        Node* curr = root;
        while(curr){   // until the current node is not NULL
            Node* leftNode = curr->left;  // at each step take its left node
            if(leftNode==NULL){ // if left node is NULL, that is doesn't exist then u have to move towards the right, and in inorder, when u make a call to right, first u store the curr->val 
                ans.push_back(curr->data);  // store the curr->val in ans vector
                curr=curr->right; /// move to the right
            }
            else{
                Node* rightMost = getRightMost(curr,leftNode);  // if left node is not NULL, then find the rightmost node of left child, since the rightmost's child's inorder successor would be curr node
                if(rightMost->right==NULL){
                    rightMost->right = curr;  // make a thread from rightmost to curr
                    curr=curr->left;  // move cur towards left child
                }
                else{
                    rightMost->right = NULL;  // if thread already exits means rightmost->right is not NULL, it is pointing to the curr, means this left tree is already processed
                    // hence u need to move towards right and whenever u move towards right in inorder, first add element to and vector
                    ans.push_back(curr->data);
                    curr=curr->right;  // move cur towards right
                }
            }
        }
            return ans;
    }
    
};
+1
hanumanmanyam8373 weeks ago
class Solution
{
    // Return a list containing the inorder traversal of the given tree
    ArrayList<Integer> inOrder(Node root)
    {
        // Code
        ArrayList<Integer>res=new ArrayList<>();
        Stack<Node>st=new Stack<>();
        while(true)
        {
            if(root!=null)
            {
                st.push(root);
                root=root.left;
            }
            else
            {
                if(st.isEmpty())
                {
                    break;
                }
                else
                {
                    root=st.pop();
                    res.add(root.data);
                    root=root.right;
                }
            }
        }
        return res;
    }
    
    
}
0
scien-terrific1 month ago
class Solution {
public:
    vector<int> inOrder(Node* root)
    {
        //code here
        vector<int>res;
        Node* cur=root;
        while(cur){
            if(!cur->left){
                res.push_back(cur->data);
                cur=cur->right;
            }
            else{
                Node* prev=cur->left;
                while(prev->right and prev->right!=cur)prev=prev->right;
                if(!prev->right){
                    prev->right=cur;
                    cur=cur->left;
                }
                else{
                    prev->right=NULL;
                    res.push_back(cur->data);
                    cur=cur->right;
                }
            }
        }
        return res;
    }
};
0
devashishbakare2 months ago
Java 
 
   ArrayList<Integer> inOrder(Node root)   {       ArrayList<Integer> ans = new ArrayList<>();              if( root == null ) return ans;              Stack<Node> stack = new Stack<>();                     while( true )       {           if( root != null){               //go to the extreme left until not found null and add nodes in stack for making the track of pervious call               stack.push(root);               root = root.left;           }           else           {               //break the loop when stack is empty               if(stack.isEmpty())               break;               else               {                   //take the item out because its extreme left and passes call to it right for checking for the same                   root = stack.peek();                   stack.pop();                   ans.add(root.data);                   root = root.right;               }           }       }       return ans;          }      }
+1
mr_coder99332 months ago
vector<int> inOrder(Node* root)
    {
        vector<int> ans;
        stack<Node*> s;
        Node* node=root;
        while(true){
            if(node){
                s.push(node);
                node=node->left;
            }else{
                if(s.empty()) break;
                node=s.top();
                s.pop();
                ans.push_back(node->data);
                node=node->right;
            }
        }
        return ans;
    }
0
prabhakarsati294262 months ago
 
def inOrder(self, root):       # code here       if root is None:           return        st = []       curr = root              while curr!= None:           st.append(curr)           curr = curr.left              while len(st)>0:           curr = st.pop()           print(curr.data,end=" ")           curr = curr.right                      while curr!=None:               st.append(curr)               curr = curr.left       return st
0
himanshu11042003singh2 months ago
SIMPLE C++ SOLUTION:-
TIME COMPLEXITY- O(N)
SPACE COMPLEXITY- O(1)
CODE-
class Solution {public:   vector<int> inOrder(Node* root)   {       //code here       vector<int>inorder;       Node* curr= root;       while(curr!=NULL){           if(curr->left==NULL){               inorder.push_back(curr->data);               curr= curr->right;           }           else{               Node* prev= curr->left;               while(prev->right&&prev->right!=curr){                   prev= prev->right;               }               if(prev->right==NULL){                   prev->right= curr;                   curr=curr->left;               }               else{                   prev->right=NULL;                   inorder.push_back(curr->data);                   curr=curr->right;               }           }       }       return inorder;   }};
0
detroix072 months ago
vector<int> inOrder(Node* root)   {          stack<Node*> s;       vector<int> v;              while(1) {         if(root!=NULL){          s.push(root);          root=root->left;         } else {           if(s.size()==0) break;           root = s.top();           s.pop();           v.push_back(root->data);           root=root->right;         }       }              return v;          }
-3
imaniket2 months ago
vector<int> inOrder(Node* root)
    {
        auto node = root;
        vector<int> ans;
        if(!root) return ans;
        stack<Node*> st;
        while(true){
            if(node){
                st.push(node);
                node= node->left;
            }
            else{
                if(st.empty()) break;
                node = st.top();
                st.pop();
                ans.push_back(node->data);
                node= node->right;
            }
        }
        return ans;
    }
-1
codewithmitesh3 months ago
vector<int> inOrder(Node *root)
{
    vector<int> ans;

    // * step 1 :- Create an empty stack S of datatype BinaryNode
    stack<Node *> s;
    // * step 2 :- Initialize current node as root
    Node *curr = root, *PoppedNode = NULL;

    while (curr != NULL || (s.empty() == false))
    {
        // * step 3 :-  Push the current node to S and set current = current->left until current is NULL
        while (curr != NULL)
        {
            s.push(curr);
            curr = curr->left;
        }
        // * Step 4 (a) :- If current is NULL and stack is not empty then Pop the top item from stack.
        PoppedNode = s.top();
        s.pop();
        // * Step 4 (b) :- Print the popped item and set current = popped_item->right
        ans.push_back(PoppedNode->data);
        curr = PoppedNode->right;
    }
    return ans;
}
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.