0

我构建了一个函数,它接受我的表达式树并计算值。我的叶节点是数字或字母作为键,但具有整数作为它们的值。当我运行程序时,我得到 -74 作为我的答案,这是不正确的。关于错误在哪里的任何线索?

                    -
                  /   \
                 +     *
               /  \   /  \
              a   /   2   +
                 / \     / \
                *       e   3
               / \
              b   c



 class bt
    {public:

        bt()
        {
        root = new tnode('-', 3, NULL);
        root->left = new tnode('+', 5, root);
        root->left->left = new tnode('a', 3, root->left);
        root->left->right = new tnode('/', 5, root->left);
        root->left->right->left = new tnode('*', 2, root->left->right);
        root->left->right->right = new tnode('d', 11, root->left->right);
        root->left->right->left->left = new tnode('b', 3, root->left->right->left);
        root->left->right->left->right = new tnode('c', 7, root->left->right->left);
        root->right = new tnode('*', 3, root);
        root->right->left = new tnode('2', 6, root->right);
        root->right->right = new tnode ('+', 1, root->right);
        root->right->right->left = new tnode ('e', 10, root->right->right);
        root->right->right->right = new tnode ('3', 3, root->right->right);
        }
  int calc(tnode *t)

{
    if(t->left==NULL && t->right == NULL)
    return t->value;
    else
    {
        int answer = 0;
        switch(t->key)
        {
            case '+':
                answer = calc(t->left)+calc(t->right);
                break;
            case '-':
                answer = calc(t->left)-calc(t->right);
                break;
            case '*':
                answer = calc(t->left)*calc(t->right);
                break;
            case '/':
                answer = calc(t->left)/calc(t->right);
                break;
        }
    return answer;  
    }
}

还有我的节点类

#ifndef tnode_H
#define tnode_H
#include <iostream>
#include <string>

using namespace std;

class tnode
{
public:
    tnode(char key, int value, tnode* p)
    {
                this->key = key;
                this->value = value;
                n = 1;
                left = NULL;
                right = NULL;
                parent = p;
    }


        tnode* left;
        tnode* right;
        tnode* parent;
        char key;
        int value;
        int n;

};




#endif
4

0 回答 0