-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathLevel order traversal in spiral form
72 lines (66 loc) · 2.12 KB
/
Level order traversal in spiral form
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
//~~~~~~~~~~~~~~~~~~~~~~~
import java.util.*;
class node{
int data;
node left;
node right;
node(int data){
this.data=data;
left=null;
right=null;
}
}
class tree{
node root;
boolean check=false;
void spiralView(){
Queue<node>q=new LinkedList<node>();
q.add(root);
while(!q.isEmpty()){
int size=q.size();
Stack<node> s=new Stack<node>();
for(int i=0;i<size;i++){
node poped=q.remove();
if(poped!=null) {
System.out.print(poped.data + ",");
}
if(check&&poped!=null) {
if (poped.left != null) {
s.push(poped.left);
}
if (poped.right != null) {
s.push(poped.right);
}
}
if(!check&&poped!=null){
if (poped.right != null) {
s.push(poped.right);
}
if (poped.left != null) {
s.push(poped.left);
}
}
}
while(!s.isEmpty()){
q.add(s.pop());
}
check=!check;
// System.out.println(q.size());
}
}
}
public class Implementation {
public static void main(String []args){
tree tree=new tree();
tree.root=new node(8);
tree.root.left = new node(3);
tree.root.right = new node(10);
tree.root.left.left = new node(1);
tree.root.left.right = new node(6);
tree.root.right.right = new node(14);
tree.root.right.right.left = new node(13);
tree.root.left.right.left = new node(4);
tree.root.left.right.right = new node(7);
tree.spiralView();
}
}