-
Notifications
You must be signed in to change notification settings - Fork 0
/
Expression Tree Build.cpp
101 lines (94 loc) · 3.22 KB
/
Expression Tree Build.cpp
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
90
91
92
93
94
95
96
97
98
99
100
101
/*
The structure of Expression Tree is a binary tree to evaluate certain expressions. All leaves of the Expression Tree have an
number string value. All non-leaves of the Expression Tree have an operator string value. Now, given an expression array,
build the expression tree of this expression, return the root of this expression tree.
Link: http://www.lintcode.com/en/problem/expression-tree-build/
Example: For the expression (2*6-(23+7)/(1+2)) (which can be represented by ["2" "*" "6" "-" "(" "23" "+" "7" ")" "/" "(" "1" "+" "2" ")"]).
Solution: None
Source: https://github.com/kamyu104/LintCode/blob/master/C%2B%2B/expression-tree-build.cpp
*/
/**
* Definition of ExpressionTreeNode:
* class ExpressionTreeNode {
* public:
* string symbol;
* ExpressionTreeNode *left, *right;
* ExpressionTreeNode(string symbol) {
* this->symbol = symbol;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param expression: A string array
* @return: The root of expression tree
*/
ExpressionTreeNode* build(vector<string> &expression) {
if (expression.empty()) {
return 0;
}
vector<string> prefix;
infixToPrefix(expression, prefix);
int start = 0;
return buildExpressionTree(prefix, start);
}
// Build expression tree by prefix expression.
ExpressionTreeNode* buildExpressionTree(vector<string>& prefix, int& start) {
if (prefix.empty()) {
return nullptr;
}
ExpressionTreeNode *node = new ExpressionTreeNode(prefix[start++]);
if (is_operator(prefix[start - 1])) {
node->left = buildExpressionTree(prefix, start);
node->right = buildExpressionTree(prefix, start);
}
return node;
}
bool is_operator(const string &op) {
return op.length() == 1 && string("+-*/").find(op) != string::npos;
}
// Convert Infix to Prefix Expression.
void infixToPrefix(vector<string>& infix, vector<string>& prefix) {
reverse(infix.begin(), infix.end());
stack<string> s;
for (auto& tok : infix) {
if (atoi(tok.c_str())) {
prefix.emplace_back(tok);
} else if (tok == ")") {
s.emplace(tok);
} else if (tok == "(") {
while (!s.empty()) {
tok = s.top();
s.pop();
if (tok == ")") {
break;
}
prefix.emplace_back(tok);
}
} else {
while (!s.empty() && precedence(tok) < precedence(s.top())) {
prefix.emplace_back(s.top());
s.pop();
}
s.emplace(tok);
}
}
while (!s.empty()) {
prefix.emplace_back(s.top());
s.pop();
}
reverse(prefix.begin(), prefix.end());
}
int precedence(string x) {
if (x == ")") {
return 0;
} else if (x == "+" || x == "-") {
return 1;
} else if (x == "*" || x == "/") {
return 2;
}
return 3;
}
};