- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpressionTreeVisualizer.java
More file actions
Latest commit
533 lines (435 loc) · 17.7 KB
/
Copy pathExpressionTreeVisualizer.java
File metadata and controls
533 lines (435 loc) · 17.7 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
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
importjavax.swing.*;
importjava.awt.*;
importjava.awt.geom.*;
importjava.util.*;
// Node class for Expression Tree
classNode {
Stringvalue;
Nodeleft, right;
Node(Stringvalue) {
this.value = value;
this.left = this.right = null;
}
booleanisOperator() {
returnvalue.equals("+") || value.equals("-") ||
value.equals("*") || value.equals("/") || value.equals("^");
}
}
// Main Expression Tree class
classExpressionTree {
privateNoderoot;
// Convert infix to postfix using stack
publicStringinfixToPostfix(Stringinfix) {
StringBuilderpostfix = newStringBuilder();
Stack<Character> stack = newStack<>();
for (inti = 0; i < infix.length(); i++) {
charc = infix.charAt(i);
// Skip whitespace
if (c == ' ') continue;
// If operand (digit or multi-digit number)
if (Character.isDigit(c)) {
while (i < infix.length() && (Character.isDigit(infix.charAt(i)) || infix.charAt(i) == '.')) {
postfix.append(infix.charAt(i++));
}
postfix.append(' ');
i--;
}
// If opening bracket
elseif (c == '(') {
stack.push(c);
}
// If closing bracket
elseif (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix.append(stack.pop()).append(' ');
}
if (!stack.isEmpty()) stack.pop(); // Remove '('
}
// If operator
else {
while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek())) {
postfix.append(stack.pop()).append(' ');
}
stack.push(c);
}
}
// Pop remaining operators
while (!stack.isEmpty()) {
postfix.append(stack.pop()).append(' ');
}
returnpostfix.toString().trim();
}
// Determine operator precedence
privateintprecedence(charop) {
switch (op) {
case'+':
case'-':
return1;
case'*':
case'/':
return2;
case'^':
return3;
default:
return -1;
}
}
// Construct expression tree from postfix
publicNodeconstructTree(Stringpostfix) {
Stack<Node> stack = newStack<>();
String[] tokens = postfix.split("\\s+");
for (Stringtoken : tokens) {
Nodenode = newNode(token);
// If operator, pop two nodes and make them children
if (node.isOperator()) {
node.right = stack.pop();
node.left = stack.pop();
}
stack.push(node);
}
root = stack.isEmpty() ? null : stack.pop();
returnroot;
}
// Evaluate expression tree recursively (postorder)
publicdoubleevaluate(Nodenode) {
if (node == null) return0;
// If leaf node (operand)
if (!node.isOperator()) {
returnDouble.parseDouble(node.value);
}
// Recursively evaluate left and right subtrees
doubleleft = evaluate(node.left);
doubleright = evaluate(node.right);
// Apply operator
switch (node.value) {
case"+": returnleft + right;
case"-": returnleft - right;
case"*": returnleft * right;
case"/": returnleft / right;
case"^": returnMath.pow(left, right);
default: return0;
}
}
// Print tree structure (console visualization)
publicvoidprintTree(Nodenode, Stringprefix, booleanisLeft) {
if (node == null) return;
System.out.println(prefix + (isLeft ? "├── " : "└── ") + node.value);
if (node.left != null || node.right != null) {
if (node.left != null) {
printTree(node.left, prefix + (isLeft ? "│ " : " "), true);
} else {
System.out.println(prefix + (isLeft ? "│ " : " ") + "├── null");
}
if (node.right != null) {
printTree(node.right, prefix + (isLeft ? "│ " : " "), false);
} else {
System.out.println(prefix + (isLeft ? "│ " : " ") + "└── null");
}
}
}
publicNodegetRoot() {
returnroot;
}
}
// GUI Panel for tree visualization
classTreePanelextendsJPanel {
privateNoderoot;
privateMap<Node, Point> nodePositions;
privateNodehighlightedNode;
privatestaticfinalintNODE_RADIUS = 30;
privatestaticfinalintLEVEL_GAP = 80;
publicTreePanel() {
nodePositions = newHashMap<>();
setPreferredSize(newDimension(850, 500));
setBackground(Color.WHITE);
}
publicvoidsetTree(Noderoot) {
this.root = root;
nodePositions.clear();
if (root != null) {
calculatePositions(root, getWidth() / 2, 50, getWidth() / 4);
}
repaint();
}
publicvoidhighlightNode(Nodenode) {
this.highlightedNode = node;
repaint();
}
privatevoidcalculatePositions(Nodenode, intx, inty, intxOffset) {
if (node == null) return;
nodePositions.put(node, newPoint(x, y));
if (node.left != null) {
calculatePositions(node.left, x - xOffset, y + LEVEL_GAP, xOffset / 2);
}
if (node.right != null) {
calculatePositions(node.right, x + xOffset, y + LEVEL_GAP, xOffset / 2);
}
}
@Override
protectedvoidpaintComponent(Graphicsg) {
super.paintComponent(g);
Graphics2Dg2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (root == null) return;
// Draw edges first
drawEdges(g2, root);
// Draw nodes
drawNodes(g2, root);
}
privatevoiddrawEdges(Graphics2Dg2, Nodenode) {
if (node == null) return;
PointnodePos = nodePositions.get(node);
g2.setStroke(newBasicStroke(2.5f));
g2.setColor(newColor(100, 100, 100));
if (node.left != null) {
PointleftPos = nodePositions.get(node.left);
g2.drawLine(nodePos.x, nodePos.y, leftPos.x, leftPos.y);
drawEdges(g2, node.left);
}
if (node.right != null) {
PointrightPos = nodePositions.get(node.right);
g2.drawLine(nodePos.x, nodePos.y, rightPos.x, rightPos.y);
drawEdges(g2, node.right);
}
}
privatevoiddrawNodes(Graphics2Dg2, Nodenode) {
if (node == null) return;
Pointpos = nodePositions.get(node);
// Simple solid colors
ColornodeColor;
if (node == highlightedNode) {
nodeColor = newColor(255, 215, 0); // Gold
} elseif (node.isOperator()) {
nodeColor = newColor(100, 149, 237); // Cornflower blue
} else {
nodeColor = newColor(60, 179, 113); // Medium sea green
}
// Draw simple circle
g2.setColor(nodeColor);
g2.fillOval(pos.x - NODE_RADIUS, pos.y - NODE_RADIUS, NODE_RADIUS * 2, NODE_RADIUS * 2);
// Draw border
g2.setColor(Color.BLACK);
g2.setStroke(newBasicStroke(2));
g2.drawOval(pos.x - NODE_RADIUS, pos.y - NODE_RADIUS, NODE_RADIUS * 2, NODE_RADIUS * 2);
// Draw text
g2.setColor(Color.WHITE);
g2.setFont(newFont("Arial", Font.BOLD, 16));
FontMetricsfm = g2.getFontMetrics();
inttextWidth = fm.stringWidth(node.value);
inttextHeight = fm.getAscent();
g2.drawString(node.value, pos.x - textWidth / 2, pos.y + textHeight / 4);
// Recursively draw children
drawNodes(g2, node.left);
drawNodes(g2, node.right);
}
}
// Main application
publicclassExpressionTreeVisualizerextendsJFrame {
privateExpressionTreetree;
privateTreePaneltreePanel;
privateJTextFieldinputField;
privateJTextAreaoutputArea;
publicExpressionTreeVisualizer() {
tree = newExpressionTree();
setupGUI();
}
privatevoidsetupGUI() {
setTitle("Expression Tree Visualizer - DSA Project");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(newBorderLayout(5, 5));
// Simple color scheme
ColorheaderColor = newColor(70, 130, 180); // Steel blue
ColorbuttonColor = newColor(100, 149, 237); // Cornflower blue
// Top panel for input
JPaneltopPanel = newJPanel(newBorderLayout(10, 10));
topPanel.setBackground(headerColor);
topPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
// Title label
JLabeltitleLabel = newJLabel("Expression Tree Visualizer");
titleLabel.setFont(newFont("Arial", Font.BOLD, 20));
titleLabel.setForeground(Color.WHITE);
// Input label
JLabellabel = newJLabel("Enter Expression:");
label.setFont(newFont("Arial", Font.PLAIN, 13));
label.setForeground(Color.WHITE);
// Input field
inputField = newJTextField("(3+5)*(2-8)");
inputField.setFont(newFont("Monospaced", Font.PLAIN, 14));
inputField.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.GRAY),
BorderFactory.createEmptyBorder(8, 10, 8, 10)
));
// Simple buttons
JButtonvisualizeBtn = newJButton("Visualize");
JButtonevaluateBtn = newJButton("Step-by-Step");
JButtonclearBtn = newJButton("Clear");
visualizeBtn.setBackground(buttonColor);
visualizeBtn.setForeground(Color.BLACK);
visualizeBtn.setFocusPainted(false);
evaluateBtn.setBackground(newColor(60, 179, 113));
evaluateBtn.setForeground(Color.BLACK);
evaluateBtn.setFocusPainted(false);
clearBtn.setBackground(newColor(220, 90, 90));
clearBtn.setForeground(Color.black);
clearBtn.setFocusPainted(false);
visualizeBtn.addActionListener(e -> visualizeExpression());
evaluateBtn.addActionListener(e -> evaluateStepByStep());
clearBtn.addActionListener(e -> {
inputField.setText("");
outputArea.setText("");
treePanel.setTree(null);
});
// Input panel
JPanelinputPanel = newJPanel(newBorderLayout(5, 5));
inputPanel.setOpaque(false);
inputPanel.add(titleLabel, BorderLayout.NORTH);
JPanelfieldPanel = newJPanel(newBorderLayout(5, 5));
fieldPanel.setOpaque(false);
fieldPanel.add(label, BorderLayout.NORTH);
fieldPanel.add(inputField, BorderLayout.CENTER);
inputPanel.add(fieldPanel, BorderLayout.CENTER);
// Button panel
JPanelbuttonPanel = newJPanel(newFlowLayout(FlowLayout.LEFT, 8, 5));
buttonPanel.setOpaque(false);
buttonPanel.add(visualizeBtn);
buttonPanel.add(evaluateBtn);
buttonPanel.add(clearBtn);
topPanel.add(inputPanel, BorderLayout.CENTER);
topPanel.add(buttonPanel, BorderLayout.SOUTH);
// Center panel for tree visualization
treePanel = newTreePanel();
treePanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.GRAY),
"Tree Structure",
javax.swing.border.TitledBorder.CENTER,
javax.swing.border.TitledBorder.TOP,
newFont("Arial", Font.BOLD, 12)
));
JScrollPanescrollPane = newJScrollPane(treePanel);
// Bottom panel for output
JPaneloutputPanel = newJPanel(newBorderLayout(5, 5));
outputPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 10));
JLabeloutputLabel = newJLabel("Output:");
outputLabel.setFont(newFont("Arial", Font.BOLD, 13));
outputArea = newJTextArea(10, 50);
outputArea.setEditable(false);
outputArea.setFont(newFont("Monospaced", Font.PLAIN, 12));
outputArea.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JScrollPaneoutputScroll = newJScrollPane(outputArea);
outputScroll.setBorder(BorderFactory.createLineBorder(Color.GRAY));
outputPanel.add(outputLabel, BorderLayout.NORTH);
outputPanel.add(outputScroll, BorderLayout.CENTER);
// Add example expressions panel
JPanelexamplesPanel = createExamplesPanel();
JPanelmainTop = newJPanel(newBorderLayout());
mainTop.add(topPanel, BorderLayout.CENTER);
mainTop.add(examplesPanel, BorderLayout.SOUTH);
// Add panels to frame
add(mainTop, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
add(outputPanel, BorderLayout.SOUTH);
setSize(900, 750);
setLocationRelativeTo(null);
}
privateJPanelcreateExamplesPanel() {
JPanelpanel = newJPanel(newFlowLayout(FlowLayout.LEFT, 8, 8));
panel.setBackground(newColor(240, 240, 240));
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY),
BorderFactory.createEmptyBorder(8, 15, 8, 15)
));
JLabelexLabel = newJLabel("Try examples:");
exLabel.setFont(newFont("Arial", Font.PLAIN, 12));
panel.add(exLabel);
String[] examples = {
"(3+5)*(2-8)",
"2^3+5*4",
"((15/(7-(1+1)))*3)-(2+(1+1))",
"10+20*30/2"
};
for (Stringex : examples) {
JButtonexBtn = newJButton(ex);
exBtn.setFont(newFont("Monospaced", Font.PLAIN, 10));
exBtn.setFocusPainted(false);
exBtn.addActionListener(e -> inputField.setText(ex));
panel.add(exBtn);
}
returnpanel;
}
privatevoidvisualizeExpression() {
try {
Stringinfix = inputField.getText().trim();
outputArea.setText("");
// Convert to postfix
Stringpostfix = tree.infixToPostfix(infix);
outputArea.append("Infix Expression: " + infix + "\n");
outputArea.append("Postfix Expression: " + postfix + "\n\n");
// Construct tree
Noderoot = tree.constructTree(postfix);
treePanel.setTree(root);
outputArea.append("Expression Tree Structure:\n");
tree.printTree(root, "", false);
// Evaluate
doubleresult = tree.evaluate(root);
outputArea.append("\n\nResult: " + result + "\n");
} catch (Exceptionex) {
outputArea.setText("Error: " + ex.getMessage());
}
}
privatevoidevaluateStepByStep() {
try {
Stringinfix = inputField.getText().trim();
Stringpostfix = tree.infixToPostfix(infix);
Noderoot = tree.constructTree(postfix);
treePanel.setTree(root);
outputArea.setText("Step-by-Step Evaluation (Postorder Traversal):\n\n");
// Create a thread to animate evaluation
newThread(() -> {
evaluateWithAnimation(root, 0);
}).start();
} catch (Exceptionex) {
outputArea.setText("Error: " + ex.getMessage());
}
}
privatedoubleevaluateWithAnimation(Nodenode, intdepth) {
if (node == null) return0;
try {
Thread.sleep(800);
} catch (InterruptedExceptione) {
e.printStackTrace();
}
SwingUtilities.invokeLater(() -> {
treePanel.highlightNode(node);
outputArea.append(" ".repeat(depth) + "Visiting: " + node.value + "\n");
});
if (!node.isOperator()) {
doublevalue = Double.parseDouble(node.value);
SwingUtilities.invokeLater(() -> {
outputArea.append(" ".repeat(depth) + " → Operand value: " + value + "\n\n");
});
returnvalue;
}
doubleleft = evaluateWithAnimation(node.left, depth + 1);
doubleright = evaluateWithAnimation(node.right, depth + 1);
doubleresult = 0;
switch (node.value) {
case"+": result = left + right; break;
case"-": result = left - right; break;
case"*": result = left * right; break;
case"/": result = left / right; break;
case"^": result = Math.pow(left, right); break;
}
finaldoublefinalResult = result;
SwingUtilities.invokeLater(() -> {
outputArea.append(" ".repeat(depth) + " → Computing: " + left + " " +
node.value + " " + right + " = " + finalResult + "\n\n");
});
returnresult;
}
publicstaticvoidmain(String[] args) {
SwingUtilities.invokeLater(() -> {
ExpressionTreeVisualizervisualizer = newExpressionTreeVisualizer();
visualizer.setVisible(true);
});
}
}