-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExpressionTreeBuild.java
More file actions
72 lines (70 loc) · 2.02 KB
/
ExpressionTreeBuild.java
File metadata and controls
72 lines (70 loc) · 2.02 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
/**
* Definition of ExpressionTreeNode:
* public class ExpressionTreeNode {
* public String symbol;
* public ExpressionTreeNode left, right;
* public ExpressionTreeNode(String symbol) {
* this.symbol = symbol;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
class TreeNode {
int val;
ExpressionTreeNode eNode;
public TreeNode(int val, String s) {
this.val = val;
eNode = new ExpressionTreeNode(s);
}
}
/**
* @param expression: A string array
* @return: The root of expression tree
*/
public ExpressionTreeNode build(String[] expression) {
if (expression == null || expression.length == 0) {
return null;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
int base = 0;
int val = 0;
for (int i = 0; i < expression.length; i++) {
if (expression[i].equals("(")) {
base += 10;
continue;
}
if (expression[i].equals(")")) {
base -= 10;
continue;
}
val = getWeight(base, expression[i]);
TreeNode node = new TreeNode(val, expression[i]);
while (!stack.isEmpty() && node.val <= stack.peek().val) {
node.eNode.left = stack.pop().eNode;
}
if (!stack.isEmpty()) {
stack.peek().eNode.right = node.eNode;
}
stack.push(node);
}
if (stack.isEmpty()) {
return null;
}
TreeNode rst = stack.pop();
while (!stack.isEmpty()) {
rst = stack.pop();
}
return rst.eNode;
}
//Calculate weight for characters
public int getWeight(int base, String s) {
if (s.equals("+") || s.equals("-")) {
return base + 1;
}
if (s.equals("*") || s.equals("/")) {
return base + 2;
}
return Integer.MAX_VALUE;
}
}