import java.io.*;
import java.util.*;
class Node {
int data;
Node left, right;
public Node(int val)
{
data = val;
left = null;
right = null;
}
}
class GFG {
static Node root = null;
static Node buildTree(String s)
{
if (s.length() == 0 || s.charAt(0) == 'N') {
return null;
}
String[] ip = s.split(" ");
root = new Node(Integer.parseInt(ip[0]));
int size = 0;
Deque<Node> q = new LinkedList<>();
q.add(root);
size++;
int i = 1;
while (size > 0 && i < ip.length) {
Node currNode = q.peek();
q.pop();
size--;
String currVal = ip[i];
if (!currVal.equals("N")) {
currNode.left
= new Node(Integer.parseInt(currVal));
q.add(currNode.left);
size++;
}
i++;
if (i >= ip.length) {
break;
}
currVal = ip[i];
if (!currVal.equals("N")) {
currNode.right
= new Node(Integer.parseInt(currVal));
q.add(currNode.right);
size++;
}
i++;
}
return root;
}
static int treeHeight(Node root)
{
if (root == null) {
return 0;
}
int lHeight = treeHeight(root.left);
int rHeight = treeHeight(root.right);
return Math.max(lHeight, rHeight) + 1;
}
static void
zigZagTraversalRecursion(Node root, int height,
boolean lor,
ArrayList<Integer> ans)
{
if (height <= 1) {
if (root != null)
ans.add(root.data);
}
else {
if (lor) {
if (root.left != null)
zigZagTraversalRecursion(
root.left, height - 1, lor, ans);
if (root.right != null)
zigZagTraversalRecursion(
root.right, height - 1, lor, ans);
}
else {
if (root.right != null)
zigZagTraversalRecursion(
root.right, height - 1, lor, ans);
if (root.left != null)
zigZagTraversalRecursion(
root.left, height - 1, lor, ans);
}
}
}
static ArrayList<Integer> zigZagTraversal(Node root)
{
ArrayList<Integer> ans = new ArrayList<Integer>();
boolean leftOrRight = true;
int height = treeHeight(root);
for (int i = 1; i <= height; i++) {
zigZagTraversalRecursion(root, i, leftOrRight,
ans);
leftOrRight = !leftOrRight;
}
return ans;
}
public static void main(String[] args)
{
String s = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15";
Node root = buildTree(s);
List<Integer> res = zigZagTraversal(root);
System.out.print(
"ZigZag traversal of binary tree is:");
for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i) + " ");
}
System.out.println();
}
}