-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSyntaxTreeArithmetic.java
More file actions
55 lines (48 loc) · 1.56 KB
/
SyntaxTreeArithmetic.java
File metadata and controls
55 lines (48 loc) · 1.56 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
class TreeNode {
String value;
TreeNode left;
TreeNode right;
TreeNode(String value) {
this.value = value;
this.left = null;
this.right = null;
}
}
public class SyntaxTreeArithmetic {
public static int traverseAndCalculate(TreeNode node) {
if (node == null) {
return 0;
}
if (node.left == null && node.right == null) {
return Integer.parseInt(node.value);
}
int leftValue = traverseAndCalculate(node.left);
int rightValue = traverseAndCalculate(node.right);
switch (node.value) {
case "+":
return leftValue + rightValue;
case "-":
return leftValue - rightValue;
case "*":
return leftValue * rightValue;
case "/":
if (rightValue == 0) {
throw new ArithmeticException("Division by zero");
}
return leftValue / rightValue;
default:
throw new IllegalArgumentException("Invalid operator: " + node.value);
}
}
public static void main(String[] args) {
// Example syntax tree: 3 + (5 * 2)
TreeNode root = new TreeNode("+");
root.left = new TreeNode("3");
root.right = new TreeNode("*");
root.right.left = new TreeNode("5");
root.right.right = new TreeNode("2");
// Perform traversal and calculation
int result = traverseAndCalculate(root);
System.out.println("Result: " + result);
}
}