Level Order ( Zigzag

import java.util.*;
public class Main {

static Scanner scn = new Scanner(System.in);

public static void main(String[] args) {
	Main m = new Main();
	BinaryTree bt = m.new BinaryTree();
	bt.levelOrderZZ();
}

private class BinaryTree {
	private class Node {
		int data;
		Node left;
		Node right;
	}

	private Node root;
	private int size;

	public BinaryTree() {
		this.root = this.takeInput(null, false);
	}

	public Node takeInput(Node parent, boolean ilc) {

		int cdata = scn.nextInt();
		Node child = new Node();
		child.data = cdata;
		this.size++;

		// left
		boolean hlc = scn.nextBoolean();

		if (hlc) {
			child.left = this.takeInput(child, true);
		}

		// right
		boolean hrc = scn.nextBoolean();

		if (hrc) {
			child.right = this.takeInput(child, false);
		}

		// return
		return child;
	}

	public void levelOrderZZ() {
		 levelOrderZZ(this.root,0);
	}
    private void levelOrderZZ(Node node,int k){
       LinkedList<Node> queue = new LinkedList<>();
       queue.addFirst(node);
       while(!queue.isEmpty()){
           Node rv = queue.removeFirst();
           System.out.print(rv.data+ " ");
           if(k%2==0){
                if(rv.left!=null){
                    queue.addLast(rv.left);
                    
                }
                if(rv.right!=null){
                    queue.addLast(rv.right);
                }
                k=k+1;
           }else{
              if(rv.right!=null){
                    queue.addLast(rv.right);
                }
            if(rv.left!=null){
                    queue.addLast(rv.left);
                }
                k=k+1; 
           }
           
       }
        
    }

}

}

Hi Vaibhav,
In this question you have to create a one more linked list of node say stack in which you add elements in place of adding them directly to queue linked list also while adding elements to stack linked list you will use the function addFirst not addLast also after adding elements you will check if queue is empty and if yes then make queue equal to stack and create a new stack linked list by using statement stack = new LinkedList<>(); and also increase the value of k here and not while adding elements.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.