-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBSTree.java
88 lines (87 loc) · 1.74 KB
/
BSTree.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
import java.util.*;
public class BSTree {
class Node{
Node left,right;
int d;
Node(int da){
d=da;
left=right=null;
}
}
Node root;
void insert(int d) {
if(root==null) {
root=new Node(d);
return;
}
Node t=root;
Node p=null;
while(t!=null) {
if(t.d==d)
return;
if(d<t.d) {
p=t;
t=t.left;
}
else {
p=t;
t=t.right;
}
}
if(d>p.d)
p.right=new Node(d);
else
p.left=new Node(d);
}
void pre(Node n){
System.out.print(n.d+",");
if(n.left==null)
return;
else
pre(n.left);
if(n.right==null)
return;
else
pre(n.right);
}
void post(Node n){
if(n==null)
return;
post(n.left);
post(n.right);
System.out.print(n.d+",");
}
void inod(Node n){
if(n==null)
return;
inod(n.left);
System.out.print(n.d+",");
inod(n.right);
}
public static void main(String args[]) {
BSTree ob=new BSTree();
char c;
do {
System.out.println("Press (1)Insert element (2)Inorder Traversal (3)Pre Order Traversal (4)Post order Traversal");
int n=new Scanner(System.in).nextInt();
switch(n) {
case 1:
System.out.print("Enter data");
ob.insert(new Scanner(System.in).nextInt());
break;
case 2:
ob.inod(ob.root);
break;
case 3:
ob.pre(ob.root);
break;
case 4:
ob.post(ob.root);
break;
default: System.out.println("Wrong choice");
}
System.out.println("Do you want to exit?(Y/N)");
c=new Scanner(System.in).next().charAt(0);
}while(c!='Y');
}
}