- Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
Latest commit
138 lines (125 loc) · 3.66 KB
/
Copy pathBinarySearchTree.java
File metadata and controls
138 lines (125 loc) · 3.66 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
importjava.util.Scanner;
publicclassBinarySearchTree {
Noderoot;
publicBinarySearchTree() {
root = null;
}
publicstaticvoidmain(String[] args) {
Scannersc = newScanner(System.in);
intch, x;
BinarySearchTreebst = newBinarySearchTree();
loop:
for (; ; ) {
System.out.print("1. Insert node\n" +
"2. Insert node using recursion\n" +
"3. In order traversal\n" +
"4. Pre order traversal\n" +
"5. Post order traversal\n" +
"6. Delete node\n" +
"0. Exit\n" +
"Enter your choice : ");
ch = sc.nextInt();
switch (ch) {
case0:
breakloop;
case1:
System.out.print("Enter the value you want to insert : ");
x = sc.nextInt();
bst.insertChild(x);
break;
case2:
System.out.print("Enter the value you want to insert : ");
x = sc.nextInt();
bst.insertChildRecursion(bst.root, x);
break;
case3:
bst.inOrder(bst.root);
break;
case4:
bst.preOrder(bst.root);
break;
case5:
bst.postOrder(bst.root);
break;
case6:
break;
default:
System.out.println("Get a pair of specs, maybe?");
}
System.out.println();
}
}
publicvoidinsertChild(intx) {
Noden = newNode(x);
Nodet = root;
if (t == null) {
root = n;
return;
}
for (; ; ) {
if (x < t.data) {
if (t.left == null) {
t.left = n;
break;
} else
t = t.left;
} else {
if (t.right == null) {
t.right = n;
break;
} else
t = t.right;
}
}
}
publicvoidinsertChildRecursion(Noden, intx) {
if (root == null) {
root = newNode(x);
return;
}
if (x < n.data) {
if (n.left == null) {
n.left = newNode(x);
} else
insertChildRecursion(n.left, x);
} else {
if (n.right == null) {
n.right = newNode(x);
} else
insertChildRecursion(n.right, x);
}
}
publicvoidinOrder(Nodex) {
if (x == null)
return;
inOrder(x.left);
System.out.print(x.data + " ");
inOrder(x.right);
}
publicvoidpreOrder(Nodex) {
if (x == null)
return;
System.out.print(x.data + " ");
inOrder(x.left);
inOrder(x.right);
}
publicvoidpostOrder(Nodex) {
if (x == null)
return;
inOrder(x.left);
inOrder(x.right);
System.out.print(x.data + " ");
}
classNode {
Nodeleft, right;
intdata;
publicNode(intdata) {
this.data = data;
left = right = null;
}
publicNode() {
data = 0;
left = right = null;
}
}
}