Level order traversal in spiral form | Practice | GeeksforGeeks

Complete the function to find spiral order traversal of a tree. For below tree, function should return 1, 2, 3, 4, 5, 6, 7.


 
 
Example 1:
Input:
      1
    /   \
   3     2
Output:1 3 2


Example 2:
Input:
           10
         /     \
        20     30
      /    \
    40     60
Output: 10 20 30 60 40 

Your Task:
The task is to complete the function findSpiral() which takes root node as input parameter and returns the elements in spiral form of level order traversal as a list. The newline is automatically appended by the driver code.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
0 <= Number of nodes <= 105
0 <= Data of a node <= 105
+1
bipulharsh12343 minutes ago
void doSpiralTraversal(stack<Node*>stk, vector<int>&spiralOutput, bool ltr=true){   if(!stk.size())       return;   stack<Node*>st;   Node *lptr, *rptr;   while(stk.size()){       lptr = stk.top()->left;       rptr = stk.top()->right;       if(ltr){           if(lptr){               spiralOutput.push_back(lptr->data);               st.push(lptr);           }           if(rptr){               spiralOutput.push_back(rptr->data);               st.push(rptr);           }       }else{           if(rptr){               spiralOutput.push_back(rptr->data);               st.push(rptr);           }           if(lptr){               spiralOutput.push_back(lptr->data);               st.push(lptr);           }       }       stk.pop();   }   doSpiralTraversal(st, spiralOutput, !ltr);}
//Function to return a list containing the level order traversal in spiral form.vector<int> findSpiral(Node *root){   //Your code here   vector<int>spiralOutput;   if(!root)       return spiralOutput;   stack<Node*>st;   st.push(root);   spiralOutput.push_back(root->data);   doSpiralTraversal(st, spiralOutput);   return spiralOutput;}
0
rajeshsurana1 day ago
Simple JAVA solution using stack
    ArrayList<Integer> findSpiral(Node root) 
    {
        ArrayList<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<Node> s = new Stack<>();
        s.push(root);
        boolean flag = false;
        while(s.isEmpty() == false) {
            Stack<Node> temp = new Stack<>();
            while (s.isEmpty() == false) {
                Node n = s.pop();
                list.add(n.data);
                if (flag) if (n.left!=null) temp.push(n.left);
                if(n.right!=null) temp.push(n.right);
                if (!flag) if (n.left!=null) temp.push(n.left);
            }
            flag = !flag;
            s = temp;
        }
        return list;
    }
 
0
harshilgupta00992 days ago
vector<int> findSpiral(Node *root)
{
    vector<int> ans;
        if(root==NULL)
            return ans;
        queue<Node*>q;
        stack<int> st;
        bool reversed=true;
        q.push(root);
        while(q.empty()==false){
            int count=q.size();
            for(int i=0;i<count;i++){
                Node* cur=q.front();
                q.pop();
                if(reversed)
                    st.push(cur->data);
                else
                    ans.push_back(cur->data);
                if(cur->left)
                    q.push(cur->left);
                if(cur->right)
                    q.push(cur->right);
            }
            if(reversed){
                while(st.empty()==false){
                    ans.push_back(st.top());
                    st.pop();
                }
            }
            reversed=!reversed;
        }
        return ans;
}
0
jagannath23sahoo4 days ago
C++:
Optimize TC O(n)
vector<int> findSpiral(Node *root)
{
    stack<Node *> s1;
    stack<Node *> s2;
    vector<int> res;
    if(root == NULL)
    {
        return {};
    }
    s1.push(root);
    while(!s1.empty() or !s2.empty())
    {
        while(!s1.empty())
        {
            Node *temp = s1.top();
            s1.pop();
            res.push_back(temp->data);
            // Push is right - left fashion
            if(temp->right != NULL)
            {
                s2.push(temp->right);
            }
            
            if(temp->left != NULL)
            {
                s2.push(temp->left);
            }
        }
        while(!s2.empty())
        {
            Node *temp = s2.top();
            s2.pop();
            res.push_back(temp->data);
            //Push in left and right fashion
            if(temp->left != NULL)
            {
                s1.push(temp->left);
            }
            if(temp->right != NULL)
            {
                s1.push(temp->right);
            }
            
        }        
    }
    return res;
}
0
lokeshdohare1231 week ago
JAVA Solution using  deque:
 
ArrayList<Integer> findSpiral(Node node)    {       // Your code here       ArrayList<Integer> ans = new ArrayList<Integer>();       if(node==null)           return ans;       ArrayDeque<Node> q = new ArrayDeque<>();              int len=0;       int flag=1;       if(node.left!=null)           q.offerLast(node.left);       if(node.right!=null)           q.offerLast(node.right);       ans.add(node.data);       while(!q.isEmpty())       {           ArrayList<Integer> temp = new ArrayList<Integer>();           len=q.size();           if(flag==1)           {               for(int i=0;i<len;i++)               {                    Node curr=q.pollFirst();                    temp.add(curr.data);                   if(curr.left!=null)                       q.offerLast(curr.left);                   if(curr.right!=null)                       q.offerLast(curr.right);                                  }               flag=0;           }           else           {               for(int i=0;i<len;i++)               {                   Node curr = q.pollLast();                   temp.add(curr.data);                   if(curr.right!=null)                       q.offerFirst(curr.right);                    if(curr.left!=null)                       q.offerFirst(curr.left);               }               flag=1;           }                     ans.addAll(temp);       }       return ans;   }
0
hanumanmanyam8371 week ago
IN JAVA
class Spiral
{
    //Function to return a list containing the level order 
    //traversal in spiral form.	
    ArrayList<Integer> findSpiral(Node root) 
    {
        Queue<Node> q=new LinkedList<>();
        ArrayList<Integer>res=new ArrayList<>();
        if(root==null)
        {
            return res;
        }
        q.add(root);
        int c=0;
        while(!q.isEmpty())
        {
            ArrayList<Integer>temp=new ArrayList<>();
            
            int count=q.size();
            for(int i=0;i<count;i++)
            {
                Node curr=q.poll();
                temp.add(curr.data);
                if(curr.left!=null)
                {
                    q.add(curr.left);
                }
                if(curr.right!=null)
                {
                    q.add(curr.right);
                }
            }
            if(c%2==0)
            {
                Collections.reverse(temp);
            }
            for(int j=0;j<temp.size();j++)
            {
                res.add(temp.get(j));
            }
            c++;
        }
        return res;
        
    }
}
0
amank07532 weeks ago
Can someone please tell why this code is failing ??
Would be very helpful!!
vector<int> v;   //Your code here   if(root==NULL)   return v;   stack<Node*> s1;   stack<Node*> s2;   s1.push(root);      while(!s1.empty() || !s2.empty())   {       while(!s1.empty())       {           Node*temp =s1.top();           s1.pop();           v.push_back(temp->data);                      if(temp->left!=NULL)           s2.push(temp->left);                      if(temp->right!=NULL)           s2.push(temp->right);       }              while(!s2.empty())       {           Node* temp1 =s2.top();           s2.pop();           v.push_back(temp1->data);                      if(temp1->left!=NULL)           s1.push(temp1->left);                      if(temp1->right!=NULL)           s1.push(temp1->right);       }   }   return v;
+2
dipanshugupta242 weeks ago
best Code with time =o(n) and space=O(N)
please upvote
vector<int> findSpiral(Node *root){   if(root==NULL)return {};   stack<struct Node*> s1;   stack<struct Node*> s2;   s1.push(root);   // int cnt=1;   vector<int> v;      while(!s1.empty()||!s2.empty()){           while(!s1.empty()){           struct Node* help=s1.top();           v.push_back(help->data);           s1.pop();           if(help->right){               s2.push(help->right);           }           if(help->left){               s2.push(help->left);           }                      }           while(!s2.empty()){               struct Node* j=s2.top();               v.push_back(j->data);               s2.pop();               if(j->left){                   s1.push(j->left);               }               if(j->right){                   s1.push(j->right);               }           }                             }   return v;   }
0
bladesurgical
This comment was deleted.
0
himanshukug19cs3 weeks ago
java solution
 
ArrayList<Integer> al = new ArrayList<>();       Stack<Node> st1 = new Stack<>();       Stack<Node> st2 = new Stack<>();       if(root==null)          return al;       st1.push(root);       al.add(root.data);       while(!st1.empty()||!st2.empty()){           if(!st1.empty()){               while(!st1.empty()){                   Node re1=st1.pop();                                      if(re1.left!=null){                      st2.push(re1.left);                      al.add(re1.left.data);                   }                   if(re1.right!=null){                      st2.push(re1.right);                      al.add(re1.right.data);                   }               }           }           else{               while(!st2.empty()){                   Node re2=st2.pop();                                  if(re2.right!=null){                      st1.push(re2.right);                      al.add(re2.right.data);                   }                   if(re2.left!=null){                      st1.push(re2.left);                       al.add(re2.left.data);                   }               }           }       }       return al;
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.