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
/**
* 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
public int num;
public String operand;
public Node left;
public Node right;
};

/**
* 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 TreeNode extends Node {

public int evaluate() {
if (this.operand == null) {
return this.num;
}
int leftTreeVal = this.left.evaluate();
int rightTreeVal = this.right.evaluate();
int ans = compute(leftTreeVal, rightTreeVal, this.operand);
return ans;
}

public TreeNode(int num) {
this.num = num;
}

public TreeNode(String operand) {
this.operand = operand;
}

public int compute(int i, int j, String operand) {
int ans = 0;
switch (operand) {
case "+":
ans = i + j;
break;
case "-":
ans = i - j;
break;
case "*":
ans = i * j;
break;
case "/":
ans = i / j;
break;
}
return ans;
}
}

class TreeBuilder {
Node buildTree(String[] postfix) {
Deque<Node> stack = new ArrayDeque<>();
for (String s : postfix) {
if (!isOperand(s)) {
stack.push(new TreeNode(Integer.parseInt(s)));
} else {
Node rightNode = stack.pop();
Node leftNode = stack.pop();
Node currNode = new TreeNode(s);
currNode.left = leftNode;
currNode.right = rightNode;
stack.push(currNode);
}
}
return stack.pop();
}

public boolean isOperand(String s) {
return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/");
}
};

/**
* Your TreeBuilder object will be instantiated and called as such:
* TreeBuilder obj = new TreeBuilder();
* Node expTree = obj.buildTree(postfix);
* int ans = expTree.evaluate();
*/

这道题还挺好玩的. OOP.

时间复杂度和空间复杂度不是重点.