Lintcode 367: Expression Tree Build (栈好题)

博客围绕表达式树构建展开,表达式树是用于计算特定表达式的二叉树,叶子节点为数字字符串,非叶子节点为操作符字符串。给出了表达式数组构建表达式树的示例,还介绍了两种解法,一是转换为逆波兰表达式并用栈处理,二是递归找优先级最低节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

367 · Expression Tree Build
Algorithms
Hard
Accepted Rate
29%
Description
Solution
Notes
Discuss
Leaderboard
Record

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.

See wiki:
Expression Tree

Example
Example 1:

Input: [“2”,"“,“6”,”-“,”(“,“23”,”+“,“7”,”)“,”/“,”(“,“1”,”+“,“2”,”)"]
Output: {[-],[
],[/],[2],[6],[+],[+],#,#,#,#,[23],[7],[1],[2]}
Explanation:
The expression tree will be like

                 [ - ]
             /          \
        [ * ]              [ / ]
      /     \           /         \
    [ 2 ]  [ 6 ]      [ + ]        [ + ]
                     /    \       /      \
                   [ 23 ][ 7 ] [ 1 ]   [ 2 ] .

After building the tree, you just need to return root node [-].
Example 2:

Input: [“10”,“+”,“(”,“3”,“-”,“5”,“)”,“+”,“7”,"“,“7”,”-",“2”]
Output: {[-],[+],[2],[+],[
],#,#,[10],[-],[7],[7],#,#,[3],[5]}
Explanation:
The expression tree will be like
[ - ]
/
[ + ] [ 2 ]
/ \
[ + ] [ * ]
/ \ /
[ 10 ] [ - ] [ 7 ] [ 7 ]
/ \
[3] [5]
After building the tree, you just need to return root node [-].
Tags
Related Problems

1908
Boolean expression evaluation
Hard

575
Decode String
Medium

368
Expression Evaluation
Hard

解法1:跟LintCode 370 Convert Expression To Reverse Polish Notation 差不多
先将表达式转换成RPN,然后处理RPN的时候,用到stack,遇到±*/的时候生成新的节点并弹栈两次,分别为新节点的右左节点。最后返回最后的那个新节点就是root。

/**
 * 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) {
        int len = expression.size();
        stack<string> optrStk;
        vector<string> RPN;
        map<string, int> prio;
        prio["+"] = 1;
        prio["-"] = 1;
        prio["*"] = 2;
        prio["/"] = 2;
        //prio["("] = 0;
        //prio[")"] = 0;
        
        //generate RPN 
        for (int i = 0; i < len; ++i) {
            string expr = expression[i];
            if (expr.size() > 1 || (expr[0] >= '0' && expr[0] <= '9')) {
                RPN.push_back(expr);
                continue;
            }
            if (expr == "(") {
                optrStk.push(expr);
                continue;
            }
            if (expr == ")") {
                while (!optrStk.empty() && optrStk.top() != "(") {
                    RPN.push_back(optrStk.top());
                    optrStk.pop();
                }
                optrStk.pop(); //pop the "("
                continue;
            }
            while (!optrStk.empty() && prio[optrStk.top()] >= prio[expr]) {
                RPN.push_back(optrStk.top());
                optrStk.pop();
            }
            optrStk.push(expr);
        }
        //dump the rest in optrStk to RPN
        while (!optrStk.empty()) {
            RPN.push_back(optrStk.top());
            optrStk.pop();
        }

        //process RPN
        ExpressionTreeNode *root;
        stack<ExpressionTreeNode *> RPNStk;
        len = RPN.size();
        if (len == 0) return NULL;
        if (len == 1) return new ExpressionTreeNode(RPN[0]); 
        for (int i = 0; i < len; i++) {
            string RPNexpr = RPN[i];
            if (RPNexpr.size() > 1 || (RPNexpr[0] >= '0' && RPNexpr[0] <= '9')) {
                RPNStk.push(new ExpressionTreeNode(RPNexpr));
            } else {
                ExpressionTreeNode *rightNode = RPNStk.top(); RPNStk.pop();
                ExpressionTreeNode *leftNode = RPNStk.top(); RPNStk.pop();
                root = new ExpressionTreeNode(RPNexpr);
                root->left = leftNode;
                root->right = rightNode;
                RPNStk.push(root);
            }
        }
        return root;
    }
};

解法2:递归。应该可以每次找到优先级最低的那个节点,然后左右递归。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值