C++ 递归计算表达式树
我构建了一个函数,它接受我的表达式树并计算值。我的叶节点是数字或字母作为键,但它们的值是整数。当我运行程序时,我得到的答案是-74,这是不正确的。有关于错误在哪里的线索吗C++ 递归计算表达式树,c++,binary-tree,expression-trees,C++,Binary Tree,Expression Trees,我构建了一个函数,它接受我的表达式树并计算值。我的叶节点是数字或字母作为键,但它们的值是整数。当我运行程序时,我得到的答案是-74,这是不正确的。有关于错误在哪里的线索吗 - / \ + * / \ / \ a / 2 + / \ / \
-
/ \
+ *
/ \ / \
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
\ifndef tnode\u H
#定义tnode_H
#包括
#包括
使用名称空间std;
类tnode
{
公众:
tnode(字符键,int值,tnode*p)
{
这个->键=键;
这个->值=值;
n=1;
左=空;
右=空;
父母=p;
}
t节点*左;
tnode*对;
tnode*父节点;
字符键;
int值;
int n;
};
#恩迪夫
答案取决于值是什么。还有,你有没有用调试器来调试过这个程序?我猜这与你如何构建树有关。你在哪里把字母散列成值?让我更新我的代码当我的函数“Return t->value”得到特定节点的数值时