forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
78 lines (69 loc) · 1.88 KB
/
Solution.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
/**
* This is the interface for the expression tree Node.
* You should not remove it, and you can define some classes to implement it.
*/
abstract class Node {
public abstract int evaluate();
// define your fields here
protected String val;
protected Node left;
protected Node right;
};
class MyNode extends Node {
public MyNode(String val) {
this.val = val;
}
public int evaluate() {
if (isNumeric()) {
return Integer.parseInt(val);
}
int leftVal = left.evaluate();
int rightVal = right.evaluate();
if (Objects.equals(val, "+")) {
return leftVal + rightVal;
}
if (Objects.equals(val, "-")) {
return leftVal - rightVal;
}
if (Objects.equals(val, "*")) {
return leftVal * rightVal;
}
if (Objects.equals(val, "/")) {
return leftVal / rightVal;
}
return 0;
}
public boolean isNumeric() {
for (char c : val.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
}
/**
* This is the TreeBuilder class.
* You can treat it as the driver code that takes the postinfix input
* and returns the expression tree represnting it as a Node.
*/
class TreeBuilder {
Node buildTree(String[] postfix) {
Deque<MyNode> stk = new ArrayDeque<>();
for (String s : postfix) {
MyNode node = new MyNode(s);
if (!node.isNumeric()) {
node.right = stk.pop();
node.left = stk.pop();
}
stk.push(node);
}
return stk.peek();
}
};
/**
* Your TreeBuilder object will be instantiated and called as such:
* TreeBuilder obj = new TreeBuilder();
* Node expTree = obj.buildTree(postfix);
* int ans = expTree.evaluate();
*/