forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathZig-Zag_tree_traversal.java
104 lines (94 loc) · 2.53 KB
/
Zig-Zag_tree_traversal.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Java implementation of a O(n) time method for
// Zigzag order traversal
import java.util.*;
public class Main {
// Class containing left and
// right child of current
// node and key value
static class Node {
public int data;
public Node left, right;
public Node(int data)
{
this.data = data;
left = right = null;
}
}
// A utility function to create a new node
static Node newNode(int data)
{
Node node = new Node(data);
return node;
}
// Function to print the zigzag traversal
static ArrayList<Integer> zigZagTraversal(Node root)
{
ArrayList<Integer> ans = new ArrayList<Integer>();
// if there is no element in the tree,return empty
// arraylist
if (root == null)
return ans;
Queue<Node> q = new LinkedList<Node>();
q.add(root);
// this variable helps to check if elements are to
// be added from left to right or right to left
boolean leftToRight = true;
while (q.size() > 0) {
int size = q.size();
// this arraylist is used to store element at
// current level
ArrayList<Integer> temp = new ArrayList<>();
for (int i = 0; i < size; i++) {
Node curr = q.poll();
if (curr.left != null)
q.add(curr.left);
if (curr.right != null)
q.add(curr.right);
temp.add(curr.data);
}
if (leftToRight) // at current level,add element
// from left to right to our
// answer
{
// do nothing
}
// we have to add element from to right to left
// and this can be done by reversing our temp
// arraylist
else {
Collections.reverse(temp);
}
// add element form temp arraylist to our ans
// arraylist
for (int i = 0; i < temp.size(); i++) {
ans.add(temp.get(i));
}
// change the value of leftToRight from true to
// false or false to true for next iteration.
leftToRight = !(leftToRight);
}
// return our ans arraylist
return ans;
}
public static void main(String[] args)
{
// Arraylist to store the traversal order.
ArrayList<Integer> ans;
// create tree
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(7);
root.left.right = newNode(6);
root.right.left = newNode(5);
root.right.right = newNode(4);
System.out.println(
"ZigZag Order traversal of binary tree is");
ans = zigZagTraversal(root);
for (int i = 0; i < ans.size();
i++) { // to print the order
System.out.print(ans.get(i) + " ");
}
}
}
// this is contributed by harsh