ZigZag Tree Traversal | Practice | GeeksforGeeks

Given a Binary Tree. Find the Zig-Zag Level Order Traversal of the Binary Tree.
 
Example 1:
Input:
        3
      /   \
     2     1
Output:
3 1 2

Example 2:
Input:
           7
        /     \
       9       7
     /  \     /   
    8    8   6     
   /  \
  10   9 
Output:
7 7 9 8 8 6 9 10 
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function zigZagTraversal() which takes the root node of the Binary Tree as its input and returns a list containing the node values as they appear in the Zig-Zag Level-Order Traversal of the Tree.
 
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
 
Constraints:
1 <= N <= 104
 
+1
karansinghyoyo77Premium5 days ago
class GFG  // If this help plzz upvote
{
    //Function to store the zig zag order traversal of tree in a list.
	ArrayList<Integer> zigZagTraversal(Node root)
	{
	     ArrayList<Integer> ans= new ArrayList<>();
        if(root==null){
            return ans;
        }
        Queue<Node> q=new LinkedList<>();
        Stack<Integer> s=new Stack<>();
        boolean reverse=false;
        q.add(root);
        while (q.isEmpty()==false){
            int count=q.size();
            for (int i = 0; i <count ; i++) {
                Node curr=q.poll();
                if(reverse==true){
                    s.push(curr.data);
                }
                else {
                    ans.add(curr.data);
                }
                if(curr.left!=null){
                    q.add(curr.left);
                }
                if(curr.right!=null){
                    q.add(curr.right);
                }

            }
            if(reverse==true){
                while (s.isEmpty()==false){
                    ans.add(s.pop());
                }
            }
            reverse=!reverse;
        }
        return ans;

	}
}
// PLzz upvote
+2
rayalravi20011 week ago
c++ solution
 
 vector<int> res;    stack<Node*>s1; // left to right;    stack<Node*>s2;  // right to left;    s1.push(root);    while(!s1.empty()|| !s2.empty()){        while(!s1.empty()){            Node *temp = s1.top();            s1.pop();            res.push_back(temp->data);            if(temp->left){                s2.push(temp->left);            }            if(temp->right)               s2.push(temp->right);        }        while(!s2.empty()){            Node *temp = s2.top();            s2.pop();            res.push_back(temp->data);            if(temp->right)              s1.push(temp->right);            if(temp->left)              s1.push(temp->left);        }    }    return res;
+1
tanashah1 week ago
vector <int> zigZagTraversal(Node* root)   {    // Code here    vector<int>v;    queue<Node*>q;    if(root==NULL){        return v;    }    int row=0;    q.push(root);    while(!q.empty()){        int size=q.size();        vector<int>ans;        for(int i=0;i<size;i++){            auto temp=q.front();            q.pop();                        if(temp->left){                q.push(temp->left);            }            if(temp->right){                q.push(temp->right);            }            ans.push_back(temp->data);        }        if(row & 1) reverse(ans.begin(),ans.end());        for(auto i:ans) v.push_back(i);//data iterate honar         row++;    }    return v;       }
0
aishapervin032 weeks ago
vector <int> zigZagTraversal(Node* root)
    {
        vector<int>ans;
    	queue<pair<Node*,char>>q;
    	q.push({root,'l'});
    	stack<int>st;
    	while(q.size()>0)
    	{
    	    int n=q.size();
    	    
    	    while(n)
    	    {
    	        Node* temp=q.front().first;
    	        char dir=q.front().second;
    	        q.pop();
    	        if(dir=='r')
    	        st.push(temp->data);
    	        else
    	        ans.push_back(temp->data);
    	        char ndir;
    	        if(dir=='l')
    	          ndir='r';
    	        else
    	          ndir='l';
    	        if(temp->left)
    	           q.push({temp->left,ndir});
    	        if(temp->right)
    	           q.push({temp->right,ndir});
    	        
    	        
    	        n--;
    	    }
    	    while(st.size()>0)
    	    {
    	        ans.push_back(st.top());
    	        st.pop();
    	    }
    	    
    	}
    	return ans;
    }
+1
hanumanmanyam8372 weeks ago
class GFG
{
    //Function to store the zig zag order traversal of tree in a list.
	ArrayList<Integer> zigZagTraversal(Node root)
	{
	    //Add your code here.
	    Queue<Node> q= new LinkedList<>();
	    ArrayList<Integer>res= new ArrayList<>();
	    if(root==null)
	    {
	        return null;
	        
	    }
	    q.add(root);
	    int c=0;
	    while(!q.isEmpty())
	    {
	        int count=q.size();
	        ArrayList<Integer>temp=new ArrayList<>();
	        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 i=0;i<temp.size();i++)
	        {
	            res.add(temp.get(i));
	        }
	        c++;
	        
	    }
	    return res;
	}
}
0
adityagagtiwari
This comment was deleted.
0
koulikmaity3 weeks ago
vector <int> zigZagTraversal(Node* root)   {    vector<int>ans;    stack<Node*>currentLevel;    stack<Node*>nextLevel;        currentLevel.push(root);    bool leftToRight = true;    while(!currentLevel.empty())    {        Node* temp = currentLevel.top();        currentLevel.pop();        if(temp)        {            ans.push_back(temp->data);            if(leftToRight)            {               if(temp->left)               {                   nextLevel.push(temp->left);               }               if(temp->right)               {                   nextLevel.push(temp->right);               }            }            else            {                if(temp->right)                {                    nextLevel.push(temp->right);                }                if(temp->left)                {                    nextLevel.push(temp->left);                }            }            if(currentLevel.empty())            {                leftToRight = !leftToRight;                swap(currentLevel,nextLevel);            }        }    }    return ans;       }
0
sumitdhanbad83 weeks ago
C++ program , well commented
vector <int> zigZagTraversal(Node* root)
   {
       // we will use 2 stacks for current lvl and next lvl
       // so that when traversal of one lvl will be completed ,we'll reverse the stacks and pop
       stack<Node*> curLvl,nxtLvl;
    curLvl.push(root);
    vector<int> v;
    // will keep track of direction of traversal and will change it at every lvl
    bool direction=1;  // direction = 1 -> left to right
    while(!curLvl.empty()){
        // to know ,whether a lvl is traversed completely or not,we will take size of curLvl
        int n=curLvl.size();
        for(int i=1;i<=n;i++){
            Node* tmp=curLvl.top();
            v.push_back(tmp->data);
            curLvl.pop();
            // now for left to right traversal, we'll push (left then right) so that after completing
            // the lvl when we'll change nxtlvl with curLvl , then we'll get the rightmost ele by top()
            if(direction){
                if(tmp->left) nxtLvl.push(tmp->left);
                if(tmp->right) nxtLvl.push(tmp->right);
                
            }else{
                if(tmp->right) nxtLvl.push(tmp->right);
                if(tmp->left) nxtLvl.push(tmp->left);
            }
        }
        // after completion of each lvl ,we'll change the direction
           direction=!direction;
           // we'll interchange the stack so that poping the top ele will give the right node
            curLvl=nxtLvl;
            
            // now we'll make the nxnLvl empty;
            while(!nxtLvl.empty()) nxtLvl.pop();
           // nxtLvl.empty();
          }
    return v;
   }
+1
prishita4 weeks ago
JAVA Solution
class GFG
{
    //Function to store the zig zag order traversal of tree in a list.
	ArrayList<Integer> zigZagTraversal(Node root)
	{
	    //Add your code here.
	    Queue<Node> q = new LinkedList<Node>();
        ArrayList<Integer> arr = new  ArrayList<Integer>();
        int flag = 0;
        
        q.add(root);
        
        while (q.size() != 0 ){
            int s = q.size();
            ArrayList<Integer> temp = new ArrayList<Integer>();
            for (int i =0; i< s; i++){
                Node n = q.peek();
                q.remove();
                temp.add(n.data);
                
                if (n.left != null) 
                    q.add(n.left);
                if (n.right != null)
                    q.add(n.right);
            }
            if (flag == 0){
               for (int i =0; i< temp.size() ; i++ )
                arr.add(temp.get(i));
               flag = 1;
            }
            else if (flag == 1){
                for (int i = temp.size()-1; i>=0; i--){
                    arr.add(temp.get(i));
                }
                flag =0 ;
            }
        }
        return arr;
	}
}
0
jaydhurat1 month ago
class GFG
{
   //Function to store the zig zag order traversal of tree in a list.
ArrayList<Integer> zigZagTraversal(Node root)
{
    Queue<Node> q = new LinkedList<>();
    ArrayList<Integer> a = new ArrayList<>();
    
    q.add(root);
    boolean flag=true;
    while(!q.isEmpty())
    {
        int size=q.size();
        List<Integer> l = new ArrayList<>(size);
        
        for(int i=0;i<size;i++)
        {
            if(q.peek().left!=null)
            {
                q.add(q.peek().left);
            }
             if(q.peek().right!=null)
            {
                q.add(q.peek().right);
            }
            
            if(flag)
            {
                l.add(q.remove().data);
            }
            else
            {
                l.add(0,q.remove().data);
            }
            
        }
        flag=!flag;
        a.addAll(l);
    }
    
    return a;
}
}
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.