【发布时间】:2016-09-06 07:56:03
【问题描述】:
我已经编写了将表达式树转换为前序和后序的代码,但我正在努力从中缀表达式实际构建表达式树。我有一个 .cc 文件,它将调用 build_expression_tree 函数,调用转换函数并打印出转换后的表达式。
这是我当前的非工作功能:
void Expression_Tree::build_expression_tree(char input[], int size)
{
for (int i = 0; i < size; i++)
{
if (input[i] == ' ')
{
i++;
}
if(input[i] >= '0' && input[i] <= 9)
{
ETNode *temp = new ETNode;
temp->left = temp->right = NULL;
temp->input = input[i];
tree_stack.push(temp);
}
else if (input[i] == '(')
{
ETNode *temp = new ETNode;
temp->left = temp->right = NULL;
temp->input = input[i];
tree_stack.push(temp);
}
else if (input[i] == ')')
{
while (tree_stack.top() != '(')
{
temp->right = tree_stack.top();
tree_stack.pop();
temp->left = tree_stack.top();
tree_stack.pop();
tree_stack.pop();
tree_stack.push(temp);
}
}
else if (input[i] == '+' || input[i] == '-' || input[i] == '*' || input[i] == '/')
{
while (!tree_stack.empty())
{
ETNode *temp = new ETNode;
temp->left = temp->right = NULL;
temp->input = input[i];
tree_stack.push(temp);
temp->right = tree_stack.top();
tree_stack.pop();
temp->left = tree_stack.top();
tree_stack.pop();
tree_stack.push(temp);
}
}
}
}
此时我遇到的错误是: Expression_Tree.h:61:40: 错误:ISO C++ 禁止指针和整数之间的比较
while(tree_stack.top() != '(')
Expression_Tree.h:62:13: 错误:'temp' 未在此范围内声明
temp->right = tree_stack.top();
Expression_Tree.h:62:13: 错误:'temp' 未在此范围内声明
temp->left = tree_stack.top();
我知道为什么会发生最后两个错误(未在范围内声明),但我只是不知道在使我的代码正常工作的同时如何修复它。
我什至不知道我的代码是否完全错误,但任何提示都将不胜感激! 谢谢。
编辑: 这些是影响 Build_Expression_Tree 函数的类。
class ETNode {
public:
char input;
ETNode *left, *right;
};
class Expression_Tree {
public:
Expression_Tree() { root = 0; };
~Expression_Tree() { clear(root); }
void build_expression_tree(char[], int);
void inorder() { inorder(root); }
void preorder() { preorder(root); }
void postorder() {postorder(root); }
private:
ETNode* root;
std::stack<ETNode*> tree_stack;
void visit(ETNode* p) { std::cout << p->input << " "; }
void inorder(ETNode*);
void preorder(ETNode*);
void postorder(ETNode*);
void clear(ETNode*);
};
【问题讨论】:
-
请告诉我们
tree_stack和ETNode是什么 -
@vu1p3n0x 我已经编辑了帖子
-
您能否澄清一下,您只是将堆栈用作构建辅助工具吗?并且只使用
root进行所有其他操作?还是您需要以某种方式保留堆栈? -
()s 在您的输入中也是强制性的吗?或者有人可以写(5 + 2 + 3)吗? -
@vu1p3n0x 堆栈纯粹用于构建树,构建函数由测试函数调用以在打印前发送到预排序/后排序函数。这些是我试图实现的步骤: 1. 将输入读入新的树节点,将它们添加到堆栈中,直到找到右括号。 2. 通过从堆栈中弹出三个项目来回溯。 3. 从这三个项目构建一个子树。 4. 从堆栈中删除匹配的左括号。 5. 将子树添加到堆栈中(实际上只是子树的根节点)。 6. 重复 1-5,直到删除所有括号。
标签: c++ stack expression-trees infix-notation