forked from kishanrajput23/Java-Projects-Collections
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBSTVisualization.java
540 lines (452 loc) · 13.9 KB
/
BSTVisualization.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
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BSTVisualization extends JFrame implements ActionListener, KeyListener {
// Tree Root Node.
private Node root;
// private Color color;
private JPanel topPanel, treePanel, infoPanel;
private JPanel topLeftPanel, topRightPanel;
private JButton btnAdd, btnDelete;
private JTextField tf;
private int X = 300, Y = 75;
private Graphics2D g2;
private Rectangle size;
private JLabel labelInorder, labelPreorder, labelPostorder, labelHeight;
private JLabel ansInorder, ansPreorder, ansPostorder, ansHeight;
private FontMetrics fontMatrix;
//Node Structure
private static class Node {
static int TEXT_WIDTH = 40;
static int TEXT_HEIGHT = 40;
JLabel data;
Node left;
Node right;
Points p;
Node(int info) {
data = new JLabel(info + "", SwingConstants.CENTER);
data.setFont(new Font("Arial", Font.BOLD, 20));
data.setBorder(BorderFactory.createLineBorder(Color.black));
data.setOpaque(true);
data.setBackground(Color.green);
p = null;
}
}
//Points structure
private static class Points {
int x1 = 0, x2 = 0, y2 = 0, y1 = 0;
Points(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.x2 = x2;
this.y2 = y2;
this.y1 = y1;
}
public String toString() {
return "x1 = " + x1 + ", y1 = " + y1 + ", x2 = " + x2 + ", y2 = " + y2;
}
}
// For storing the Height of the root,left and right child height.
private static class Height {
int root, left, right;
Height() {
this.root = 0;
this.left = 0;
this.right = 0;
}
Height(int left, int right) {
this.left = left;
this.right = right;
}
@Override
public String toString() {
return Integer.toString(this.root);
}
}
public void paint(Graphics g) {
super.paintComponents(g);
g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(3.0f));
Stack<Node> s = new Stack<>();
Node curr = root;
Points pts;
int offset = topPanel.getBounds().height;
while (!s.isEmpty() || curr != null) {
while (curr != null) {
s.push(curr);
curr = curr.left;
}
if (!s.isEmpty())
curr = s.pop();
pts = curr.p;
g2.drawLine(pts.x1 + 7, pts.y1 + 30 + offset, pts.x2 + 3, pts.y2 + 10 + offset);
curr = curr.right;
}
// x1 = label.getX()+7
// y1 = label.getY()+30
}
public BSTVisualization() {
// Initialize the frame.
initialize();
}
private void initialize() {
// setLayout(null); // layout
setSize(1200, 700); //frame size
size = getBounds();
X = size.width / 2;
topPanel = new JPanel(new BorderLayout());
Rectangle top = topPanel.getBounds();
topLeftPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
topPanel.add(topLeftPanel, BorderLayout.WEST);
topRightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
topPanel.add(topRightPanel, BorderLayout.EAST);
treePanel = new JPanel(null);
treePanel.setPreferredSize(new Dimension(size.width, size.height - 300));
infoPanel = new JPanel();
infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
infoPanel.setPreferredSize(new Dimension(size.width, 200));
// Height of BST label
labelHeight = new JLabel("BST Height : ");
labelHeight.setFont(new Font("Calibri", Font.BOLD, 20));
topLeftPanel.add(labelHeight);
// Height of BST answer
ansHeight = new JLabel("0");
ansHeight.setFont(new Font("Calibri", Font.BOLD, 20));
ansHeight.setPreferredSize(new Dimension(50, 30));
topLeftPanel.add(ansHeight);
//For geting data.
tf = new JTextField("");
tf.setFont(new Font("Arial", Font.BOLD, 20));
tf.setPreferredSize(new Dimension(150, 30));
tf.addKeyListener(this);
topRightPanel.add(tf);
//Add Button
btnAdd = new JButton("Add");
btnAdd.setFont(new Font("Arial", Font.BOLD, 20));
// btnAdd.setBounds(size.width - 130, 20, 100, 30);
btnAdd.addActionListener(this);
topRightPanel.add(btnAdd);
//Delete Button
btnDelete = new JButton("Delete");
btnDelete.setFont(new Font("Arial", Font.BOLD, 20));
// btnDelete.setBounds(size.width - 130, 60, 100, 30);
btnDelete.addActionListener(this);
topRightPanel.add(btnDelete);
// Inorder label
labelInorder = new JLabel("Inorder :");
labelInorder.setFont(new Font("Times New Roman", Font.BOLD, 20));
infoPanel.add(labelInorder);
infoPanel.add(Box.createRigidArea(new Dimension(7, 5)));
// Inorder traversal answer
ansInorder = new JLabel("BST is empty.");
ansInorder.setFont(new Font("Arial", Font.PLAIN, 18));
infoPanel.add(ansInorder);
infoPanel.add(Box.createRigidArea(new Dimension(7, 15)));
// Preorder label
labelPreorder = new JLabel("Preorder :");
labelPreorder.setFont(new Font("Times New Roman", Font.BOLD, 20));
infoPanel.add(labelPreorder);
infoPanel.add(Box.createRigidArea(new Dimension(7, 5)));
// Preorder traversal answer
ansPreorder = new JLabel("BST is empty.");
ansPreorder.setFont(new Font("Arial", Font.PLAIN, 18));
infoPanel.add(ansPreorder);
infoPanel.add(Box.createRigidArea(new Dimension(7, 15)));
// Postorder label
labelPostorder = new JLabel("Postorder :");
labelPostorder.setFont(new Font("Times New Roman", Font.BOLD, 20));
infoPanel.add(labelPostorder);
// Postorder traversal answer
ansPostorder = new JLabel("BST is empty.");
ansPostorder.setFont(new Font("Arial", Font.PLAIN, 18));
infoPanel.add(ansPostorder);
tf.requestFocusInWindow();
add(topPanel, BorderLayout.NORTH);
add(treePanel, BorderLayout.CENTER);
add(infoPanel, BorderLayout.SOUTH);
setTitle("Binary Search Tree Visualization"); //Title Frame
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent evt) {
if (tf.isEnabled()) {
try {
int data = Integer.parseInt(tf.getText());
if (evt.getSource() == btnAdd) {
add(data);
} else {
delete(data);
}
tf.setText("");
tf.requestFocusInWindow();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Please Enter Integer.");
}
}
}
@Override
public void keyTyped(KeyEvent evt) {
char c = evt.getKeyChar();
if (!tf.isEnabled()) {
return;
} else if (c == 'a' || c == 'A' || c == '\n') {
try {
String data = tf.getText();
evt.consume(); // Not type 'a' or 'A' character in textfield
if (!data.isEmpty()) {
add(Integer.parseInt(data));
} else {
throw new Exception();
}
tf.requestFocusInWindow();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Please Enter Integer.");
}
tf.setText("");
} else if (c == 'd' || c == 'D') {
try {
String data = tf.getText();
evt.consume(); // Not type 'd' or 'D' character in textfield
if (!data.isEmpty()) {
delete(Integer.parseInt(data));
}
tf.requestFocusInWindow();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Please Enter Integer.");
}
tf.setText("");
} else if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
evt.consume();
}
@Override
public void keyPressed(KeyEvent evt) {
}
@Override
public void keyReleased(KeyEvent evt) {
}
//Add element in BST.
public void add(int info) {
Node newNode = new Node(info);
int width = getWidth(newNode);
if (root == null) {
root = newNode;
newNode.data.setBounds(treePanel.getBounds().width / 2, 10, width, 40);
newNode.p = new Points(0, 0, 0, 0);
} else {
Node curr = root, pre = root;
int currData;
X = treePanel.getBounds().width / 2;
while (curr != null) {
pre = curr;
currData = Integer.parseInt(curr.data.getText());
if (info == currData) {
JOptionPane.showMessageDialog(null, info + " is already exist.");
return;
} else if (currData > info) {
curr = curr.left;
} else {
curr = curr.right;
}
X /= 2;
}
currData = Integer.parseInt(pre.data.getText());
int x = pre.data.getX();
int y = pre.data.getY();
Dimension preDimension = pre.data.getSize();
Dimension currDimension = new Dimension(width, Node.TEXT_HEIGHT);
if (currData > info) {
pre.left = newNode;
newNode.data.setBounds(x - X, y + Y, width, 40);
// x1=x;y1=y+20;x2=x-X+20;y2=y+Y+20;
newNode.p = new Points(x, y + preDimension.height / 2, x - X + currDimension.width / 2, y + Y + currDimension.height / 2);
} else {
pre.right = newNode;
newNode.data.setBounds(x + X, y + Y, width, 40);
// x1=x+40;y1=y+20;x2=x+X+20;y2=y+Y+20;
newNode.p = new Points(x + preDimension.width, y + preDimension.height / 2, x + X + currDimension.width / 2, y + Y + currDimension.height / 2);
}
}
// Set all traversal and height of BST
setInfo();
// paint(treePanel.getGraphics());
treePanel.add(newNode.data);
treePanel.validate();
treePanel.repaint();
validate();
repaint();
}
// Delete Node from BST
public void delete(int data) {
if (root == null) {
JOptionPane.showMessageDialog(null, "BST is empty.");
} else {
Node curr = root, pre = root;
while (curr != null) {
int info = Integer.parseInt(curr.data.getText());
if (info == data) {
break;
} else if (info > data) {
pre = curr;
curr = curr.left;
} else {
pre = curr;
curr = curr.right;
}
}
if (curr == null) { // data is not find.
JOptionPane.showMessageDialog(null, data + " is not available.");
return;
} else if (curr.left == null || curr.right == null) { // data has 0 or 1 child
treePanel.remove(curr.data);
treePanel.validate();
treePanel.repaint();
validate();
repaint();
if (curr != root) {
Node address = curr.left != null ? curr.left : curr.right;
// curr.data>pre.data
int preData = Integer.parseInt(pre.data.getText());
int currData = Integer.parseInt(curr.data.getText());
if (currData > preData) {
pre.right = address;
} else {
pre.left = address;
}
} else {
if (curr.left != null) {
root = curr.left;
} else {
root = curr.right;
}
}
} else { // data has 2 child.
treePanel.remove(curr.data);
treePanel.validate();
treePanel.repaint();
validate();
repaint();
/*
It set another node depending upon the height of left and right sub tree.
*/
Node nextRoot = null, preRoot = curr;
Height height = calculateHeight(curr);
/* For taking maximum element from the left Side. */
if (height.left > height.right) {
nextRoot = curr.left;
while (nextRoot.right != null) {
preRoot = nextRoot;
nextRoot = nextRoot.right;
}
if (preRoot != curr) {
preRoot.right = nextRoot.left;
} else {
preRoot.left = nextRoot.left;
}
} else { /* For taking minimum element from the right Side.*/
nextRoot = curr.right;
while (nextRoot.left != null) {
preRoot = nextRoot;
nextRoot = nextRoot.left;
}
if (preRoot != curr) {
preRoot.left = nextRoot.right;
} else {
preRoot.right = nextRoot.right;
}
}
curr.data = nextRoot.data;
}
reArrangeNode(root, root, treePanel.getBounds().width / 2);
}
// Set all traversal and height of BST
setInfo();
}
// Set all traversal and height of BST
private void setInfo() {
Height height = calculateHeight(root);
if (height.root == 0) {
ansInorder.setText("BST is empty.");
ansPostorder.setText("BST is empty.");
ansPreorder.setText("BST is empty.");
} else {
ansInorder.setText(inorder(root));
ansPostorder.setText(postorder(root));
ansPreorder.setText(preorder(root));
}
ansHeight.setText(height.root + "");
}
private int getWidth(Node node) {
fontMatrix = getFontMetrics(node.data.getFont());
int width = fontMatrix.stringWidth(node.data.getText());
return width < Node.TEXT_WIDTH ? Node.TEXT_WIDTH : (width + 5);
}
//Inorder logic
private String inorder(Node root) {
if (root == null)
return "";
return inorder(root.left) + root.data.getText() + " " + inorder(root.right);
}
//Preorder logic
public String preorder(Node root) {
if (root == null)
return "";
return root.data.getText() + " " + preorder(root.left) + preorder(root.right);
}
//Postorder logic
public String postorder(Node root) {
if (root == null)
return "";
return postorder(root.left) + postorder(root.right) + root.data.getText() + " ";
}
// Calculate Height of BST using recursive method.
private Height calculateHeight(Node root) {
if (root == null) {
return new Height();
}
Height leftChild = calculateHeight(root.left);
Height rightChild = calculateHeight(root.right);
Height current = new Height(leftChild.root, rightChild.root);
current.root = 1 + Math.max(leftChild.root, rightChild.root);
return current;
}
// Rearrange nodes
private void reArrangeNode(Node node, Node pre, int X) {
if (node == null)
return;
int width = getWidth(node);
if (root == node) {
node.data.setBounds(X, 10, width, Node.TEXT_HEIGHT);
} else {
int x = pre.data.getX();
int y = pre.data.getY();
Dimension preDimension = pre.data.getSize();
Dimension currDimension = new Dimension(width, Node.TEXT_HEIGHT);
int preData = Integer.parseInt(pre.data.getText());
int nodeData = Integer.parseInt(node.data.getText());
if (nodeData < preData) {
node.data.setBounds(x - X, y + Y, width, Node.TEXT_HEIGHT);
node.p = new Points(x, y + preDimension.height / 2, x - X + currDimension.width / 2, y + Y + currDimension.height / 2);
} else {
node.data.setBounds(x + X, y + Y, width, Node.TEXT_HEIGHT);
// node.p = new Points(x + 40, y + 20, x + X + 20, y + Y + 20);
node.p = new Points(x + preDimension.width, y + preDimension.height / 2, x + X + currDimension.width / 2, y + Y + currDimension.height / 2);
}
}
reArrangeNode(node.left, node, X / 2);
reArrangeNode(node.right, node, X / 2);
}
public static void main(String arg[]) {
BSTVisualization bst = new BSTVisualization();
bst.add(500);
bst.add(250);
bst.add(350);
bst.add(200);
bst.add(750);
bst.add(1000);
bst.add(700);
bst.add(740);
}
}