简体   繁体   English

使用堆栈构建表达式树

[英]Using a stack to build an expression tree

I'm attempting to write an expression tree function that takes in a character array expression and outputs the prefix, infix and postfix version. 我正在尝试编写一个表达式树函数,该函数接受一个字符数组表达式并输出前缀,中缀和后缀版本。 I have written this code and it doesn't throw any errors, but when run the calculated values don't print out. 我已经编写了这段代码,它不会引发任何错误,但是运行时不会打印出计算出的值。 I've tried to debug the function but still cannot come up with a solution. 我尝试调试该函数,但仍然无法提出解决方案。 Is anyone able to give me any tips about what I'm doing wrong with this? 有谁能给我有关我做错了什么的提示?

void Expression_Tree::build_expression_tree(char input[], int size)
{
    ETNode *temp, *t1, *t2;

    for (int i = 0; i < size; i++)
    {
        if(!(i == '+' || i == '-' || i == '*' || i == '/' || i == '^')) {
            temp = new ETNode;
            temp->left = temp->right = NULL;
            temp->input = i;

            tree_stack.push(temp);
        }
        else {
            temp = new ETNode;
            temp->left = temp->right = NULL;
            temp->input = i;

            t1 = tree_stack.top();
            tree_stack.pop();
            t2 = tree_stack.top();
            tree_stack.pop();

            temp->right = t1;
            temp->left = t2;

            tree_stack.push(temp);
        }
    }

    temp = tree_stack.top();
    tree_stack.pop();
}

I've just included the build_expression_tree function, if there is nothing deemed wrong with this then it mustn't be linking to my inorder, preorder and postorder functions properly. 我刚刚包含了build_expression_tree函数,如果这没有什么不对的地方,那么它一定不能正确地链接到我的order,preorder和postorder函数。 Thanks! 谢谢!

It may be a copy-paste error, but you're using i as if it was a char . 可能是复制粘贴错误,但是您使用i就像是char

I guess you want to use input[i] instead, at least in your if statement. 我猜想至少在if语句中要使用input[i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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