简体   繁体   中英

Build binary expression tree C++

I made an algorithm that builds a binary tree from a simple expression. But I need brackets for every action. for example I can convert this expression: (2+(3*5)) . In maths everything is ok if there are not any brackets, but my algorithm can work without them. Is there a way to make an algorithm that can make a binary expression tree that works with this expression: 2+3*5 ? Here is my algorithm that needs brackets for every action:

void Tree::MakeTree(string expr, int &pos, Node *node)
{
    if(expr[pos] == '(')
    {
        pos++;
        node->Left = new Node;
        node->Left->Left = NULL;
        node->Left->Right = NULL;
        MakeTree(expr, pos, node->Left);
        MakeTree(expr, pos, node);
        return;
    }

    if(expr[pos] >= '0' && expr[pos] <= '9')
    {
        node->data = expr[pos];
        pos++;
        return;
    }

    if(expr[pos] == '+' || expr[pos] == '-' || expr[pos] == '*' || expr[pos] == '/')
    {
        node->data = expr[pos];
        pos++;
        node->Right = new Node;
        node->Right->Left = NULL;
        node->Right->Right = NULL;
        MakeTree(expr, pos, node->Right);
    }

    if(expr[pos] == ')') 
        {
            pos++;
            return;
        }
}

If you can offer solution for optimizing my algorithm will be awesome, because I feel that it is not very good.

The way you are trying to solve your problem is too simplified. That would not work. Why? Because how you react on particular symbol depends not only on symbol itself, but in which context you are getting that symbol. So you would have to implement a state machine and in different states you would react differently even to the same input. For example, when you get symbol '-' what is it, part of expression like '5-3' or unary minus from '-6'? It depends in which state you are when you received that symbol. So implementation of full logic of processing syntax parsing is not that simple and which is worse pretty monotonic. That's why in real programs people usually not doing that manually but using special tools like lex/flex or boost library spirit etc. It does not mean you cannot implement that for learning, but answer to that question probably would be too big for stackoverflow format, and it is already answered in many books. So find a good book for syntax parsing or try to find tutorial on internet how to implement a simple calculator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM