Skip to content

Commit ffccee2

Browse files
committed
spiral traverse of bst
1 parent cc453ca commit ffccee2

File tree

1 file changed

+129
-0
lines changed

1 file changed

+129
-0
lines changed

Assignments/spiraltraverse.java

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import java.util.*;
2+
public class spiraltraverse
3+
{
4+
Node root;
5+
class Node
6+
{
7+
int data;
8+
Node right,left;
9+
Node(int data)
10+
{
11+
this.data=data;
12+
right=left=null;
13+
}
14+
}
15+
void insert(int data) {
16+
root = insertRec(root,data);
17+
}
18+
Node insertRec(Node root, int data) {
19+
if (root == null) {
20+
root = new Node(data);
21+
return root;
22+
}
23+
if (data < root.data)
24+
root.left = insertRec(root.left, data);
25+
else if (data > root.data)
26+
root.right = insertRec(root.right, data);
27+
return root;
28+
}
29+
void printrtllevel(Node root , int level)
30+
{
31+
if(root == null)
32+
{
33+
return;
34+
}
35+
if(level == 1)
36+
{
37+
System.out.print(root.data + " " );
38+
}
39+
else if(level>1)
40+
{
41+
printrtllevel(root.right, level-1);
42+
printrtllevel(root.left, level-1);
43+
}
44+
}
45+
void printlevel(Node root , int level)
46+
{
47+
if(root == null)
48+
{
49+
return;
50+
}
51+
if(level == 1)
52+
{
53+
System.out.print(root.data + " " );
54+
}
55+
else if(level>1)
56+
{
57+
printlevel(root.left, level-1);
58+
printlevel(root.right, level-1);
59+
}
60+
}
61+
int height()
62+
{
63+
int a ;
64+
a = calHeight(root);
65+
return a;
66+
}
67+
int calHeight(Node root)
68+
{
69+
if(root == null)
70+
{
71+
return 0;
72+
}
73+
else
74+
{
75+
int l = calHeight(root.left);
76+
int r = calHeight(root.right);
77+
if(l>r)
78+
{
79+
return l+1;
80+
}
81+
else
82+
{
83+
return r+1;
84+
}
85+
}
86+
}
87+
void spiral()
88+
{
89+
printinSpiral(root);
90+
}
91+
void printinSpiral(Node root)
92+
{
93+
int h = height();
94+
for(int i = 1 ; i<=h ; i++)
95+
{
96+
if(i%2==1)
97+
{
98+
printrtllevel(root, i);
99+
System.out.println();
100+
}
101+
else
102+
{
103+
printlevel(root, i);
104+
System.out.println();
105+
}
106+
}
107+
}
108+
109+
public static void main(String []agrs)
110+
{
111+
spiraltraverse tree = new spiraltraverse();
112+
Scanner sc = new Scanner(System.in);
113+
System.out.println("Enter the number of nodes");
114+
int num = sc.nextInt();
115+
System.out.println("Enter nodes");
116+
/*Enter the data nodes in PreOrder or just enter root node first*/
117+
for(int i =0 ; i<num ; i++)
118+
{
119+
tree.insert(sc.nextInt());
120+
}
121+
tree.spiral();
122+
123+
124+
125+
}
126+
127+
128+
129+
}

0 commit comments

Comments
 (0)