Expression Tree Build
Description:
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.
Example,
For the expression (26-(23+7)/(1+2))* (which can be represented by ["2" "*" "6" "-" "(" "23" "+" "7" ")" "/" "(" "1" "+" "2" ")"]). The expression tree will be like
[ - ]
/ \
[ * ] [ / ]
/ \ / \
[ 2 ] [ 6 ] [ + ] [ + ]
/ \ / \
[ 23 ][ 7 ] [ 1 ] [ 2 ] .
After building the tree, you just need to return root node [-].
Clarification
Solution:
/**
* 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) {
auto sz = (int)expression.size();
if (sz == 0) return nullptr;
stack<ExpressionTreeNode*> ops;
stack<ExpressionTreeNode*> nums;
unordered_map<string, int> cache;
cache["+"] = cache["-"] = 1;
cache["*"] = cache["/"] = 2;
for (int i = 0; i < sz; ++i) {
auto ch = expression[i];
if (ch == "+" || ch == "-" || ch == "*" || ch == "/") {
if (ops.empty()) {
ops.push(new ExpressionTreeNode(ch));
} else {
auto top = ops.top();
auto sym = top->symbol;
if (sym == "(" || cache[sym] < cache[ch]) {
ops.push(new ExpressionTreeNode(ch));
} else {
ops.pop();
auto num1 = nums.top();
nums.pop();
auto num2 = nums.top();
nums.pop();
top->left = num2;
top->right = num1;
nums.push(top);
--i;
}
}
} else if (ch == "(") {
ops.push(new ExpressionTreeNode(ch));
} else if (ch == ")") {
auto top = ops.top();
auto sym = top->symbol;
if (sym == "(") ops.pop();
else {
ops.pop();
auto num1 = nums.top();
nums.pop();
auto num2 = nums.top();
nums.pop();
top->left = num2;
top->right = num1;
nums.push(top);
--i;
}
} else {
nums.push(new ExpressionTreeNode(ch));
}
}
while (!ops.empty()) {
auto op = ops.top();
ops.pop();
auto num1 = nums.top();
nums.pop();
auto num2 = nums.top();
nums.pop();
op->left = num2;
op->right = num1;
nums.push(op);
}
return nums.empty() ? nullptr : nums.top();
}
};