-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBfs.java
More file actions
112 lines (105 loc) · 2.2 KB
/
Copy pathBfs.java
File metadata and controls
112 lines (105 loc) · 2.2 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
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
105
106
107
108
109
110
111
class node
{
int data;
node left;
node right;
public node(int data)
{
this.data=data;
this.left=null;
this.right=null;
}
}
class Bfs
{
node root;
public void insert(int data)
{
root=insertrec(root,data);
}
public node insertrec(node root,int data)
{
if(root== null)
{
root=new node(data);
}
else if(data<root.data)
{
root.left=insertrec(root.left,data);
}
else
{
root.right=insertrec(root.right,data);
}
return root;
}
public void inorder(node root)
{
if(root!=null)
{
inorder(root.left);
System.out.print(root.data+" ");
inorder(root.right);
}
}
public void preorder(node root)
{
if(root!=null)
{
System.out.print(root.data+" ");
preorder(root.left);
preorder(root.right);
}
}
public void postorder(node root)
{
if(root!=null)
{
postorder(root.left);
postorder(root.right);
System.out.print(root.data+" ");
}
}
public int height(node root)
{
if(root==null)
{
return 0;
}
return 1 + Math.max(height(root.left),height(root.right));
}
public void bfs(node root,int level)
{
if(root==null)
{
return;
}
if(level==1)
{
System.out.print(root.data+" ");
}
bfs(root.left,level-1);
bfs(root.right,level-1);
}
public static void main(String args[])
{
Bfs r=new Bfs();
r.insert(5);
r.insert(6);
r.insert(3);
r.insert(10);
r.insert(2);
System.out.println("inorder");
r.inorder(r.root);
System.out.println("\npostorder");
r.postorder(r.root);
System.out.println("\npreorder");
r.preorder(r.root);
int h=r.height(r.root);
System.out.println("\nBFS (level-order):");
for(int i=1;i<=h;i++)
{
r.bfs(r.root,i);
}
}
}