-
Notifications
You must be signed in to change notification settings - Fork 22
/
EvaluationOfExpression.java
74 lines (59 loc) · 1.97 KB
/
EvaluationOfExpression.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
package com.company.amazon;
import java.util.Arrays;
import java.util.List;
public class EvaluationOfExpression {
static List<String> supportedOperations = Arrays.asList("+", "/", "*", "-");
public static class Node {
Node left;
Node right;
String data;
Node(String data) {
this.data = data;
}
}
public static void main(String[] args) {
Node head = new Node("+");
head.left = new Node("*");
head.right = new Node("-");
head.left.left = new Node("5");
head.left.right = new Node("4");
head.right.left = new Node("100");
head.right.right = new Node("20");
System.out.println(evaluateExpression(head));
head = new Node("+");
head.left = new Node("*");
head.right = new Node("-");
head.left.left = new Node("5");
head.left.right = new Node("4");
head.right.left = new Node("100");
head.right.right = new Node("/");
head.right.right.left = new Node("20");
head.right.right.right = new Node("2");
System.out.println(evaluateExpression(head));
}
public static int evaluateExpression(Node root) {
if (root == null) {
return 0;
}
if (supportedOperations.contains(root.data)) {
int left = evaluateExpression(root.left);
int right = evaluateExpression(root.right);
root.data = String.valueOf(evaluate(left, right, root.data));
}
return Integer.parseInt(root.data);
}
public static int evaluate(int operand1, int operand2, String operator) {
switch (operator) {
case "+":
return operand1 + operand2;
case "*":
return operand1 * operand2;
case "-":
return operand1 - operand2;
case "/":
return operand1 / operand2;
default:
return 0;
}
}
}