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.

Have you met this question in a real interview?

Yes

Clarification

See wiki:
Expression Tree

Example

For the expression(2*6-(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[-].

/**

* 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\) {

    // write your code here

    stack<ExpressionTreeNode\*> s1;

    stack<string> s2;

    for \(string& s : expression\) {

        if \(s == "\("\) {

            s2.push\(s\);

        } else if \(s == "\)"\) {

            while \(s2.top\(\) != "\("\) {

                buildTree\(s1, s2\);

            }

            s2.pop\(\);

        } else {

            if \(!IsOperator\(s\)\) {

                s1.push\(new ExpressionTreeNode\(s\)\);

            } else {

                while \(!s2.empty\(\) && Precedence\(s2.top\(\)\) >= Precedence\(s\)\) {

                    buildTree\(s1, s2\);    

                }

                s2.push\(s\);

            }

        }

    }



    while \(!s2.empty\(\)\) {

        buildTree\(s1, s2\);

    }



    if \(s1.empty\(\)\) {

        return NULL;

    }

    return s1.top\(\);

}



void buildTree\(stack<ExpressionTreeNode\*>& s1, stack<string>& s2\) {

    ExpressionTreeNode\* node = new ExpressionTreeNode\(s2.top\(\)\);

    s2.pop\(\);

    node->right = s1.top\(\); s1.pop\(\);

    node->left = s1.top\(\); s1.pop\(\);

    s1.push\(node\);

}



bool IsOperator\(string& s\) {

    return s == "+" \|\| s == "-" \|\| s == "\*" \|\| s == "/";

}



int Precedence\(string& op\) {

    if \(op == "+" \|\| op == "-"\) {

        return 1;

    }

    if \(op == "\*" \|\| op == "/"\) {

        return 2;

    }

    return 0;

}

};

results matching ""

    No results matching ""