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();
    }
};

转载于:https://www.cnblogs.com/deofly/p/expression-tree-build.html

这是上题的代码:def infix_to_postfix(expression): precedence = {'!': 3, '&': 2, '|': 1, '(': 0} op_stack = [] postfix_list = [] token_list = expression.split() for token in token_list: if token.isalnum(): postfix_list.append(token) elif token == '(': op_stack.append(token) elif token == ')': top_token = op_stack.pop() while top_token != '(': postfix_list.append(top_token) top_token = op_stack.pop() else: # operator while op_stack and precedence[op_stack[-1]] >= precedence[token]: postfix_list.append(op_stack.pop()) op_stack.append(token) while op_stack: postfix_list.append(op_stack.pop()) return ' '.join(postfix_list) class Node: def __init__(self, value): self.value = value self.left_child = None self.right_child = None def build_expression_tree(postfix_expr): operator_stack = [] token_list = postfix_expr.split() for token in token_list: if token.isalnum(): node = Node(token) operator_stack.append(node) else: right_node = operator_stack.pop() left_node = operator_stack.pop() node = Node(token) node.left_child = left_node node.right_child = right_node operator_stack.append(node) return operator_stack.pop() def evaluate_expression_tree(node, variable_values): if node.value.isalnum(): return variable_values[node.value] else: left_value = evaluate_expression_tree(node.left_child, variable_values) right_value = evaluate_expression_tree(node.right_child, variable_values) if node.value == '!': return not left_value elif node.value == '&': return left_value and right_value elif node.value == '|': return left_value or right_value expression = "!a & (b | c)" postfix_expression = infix_to_postfix(expression) expression_tree = build_expression_tree(postfix_expression) variable_values = {'a': True, 'b': False, 'c': True} result = evaluate_expression_tree(expression_tree, variable_values) print(result)
06-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值