-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZigZag.java
More file actions
75 lines (61 loc) · 1.22 KB
/
Copy pathZigZag.java
File metadata and controls
75 lines (61 loc) · 1.22 KB
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
package practice;
import java.util.*;
class Node{
int data;
Node left;
Node right;
Node(int d){
Node left, right=null;
data=d;
}
}
class tree{
Node root;
boolean lTr=false;
tree(){
root=null;
}
void printZigZagTraversal()
{
Stack<Node> curr=new Stack<>();
Stack<Node> next=new Stack<>();
curr.push(root);
lTr=true;
while(!curr.isEmpty()) {
Node x=curr.pop();
System.out.print(x.data+" ");
if(lTr) {
if(x.left!=null)
next.push(x.left);
if(x.right!=null)
next.push(x.right);
}
else {
if(x.right!=null)
next.push(x.right);
if(x.left!=null)
next.push(x.left);
}
if(curr.isEmpty()) {
lTr=!lTr;
Stack<Node> temp=curr;
curr=next;
next=temp;
}
}
}
}
public class Zigzag {
public static void main(String[] args) {
tree tree = new tree();
tree.root = new Node(2);
tree.root.left = new Node(5);
tree.root.right = new Node(7);
tree.root.left.left = new Node(3);
tree.root.left.right = new Node(1);
tree.root.right.left = new Node(9);
tree.root.right.right = new Node(8);
System.out.println("ZigZag Order traversal of binary tree is");
tree.printZigZagTraversal();
}
}