我正在尝试使用抽象语法树来获取反向波兰语符号方程,并将其更改为其等效的中缀形式。下面是我们最初用来打印树的AST和print_table的结构。
struct tnode {
char *datum;
struct tnode *left;
struct tnode *right;
};
void print_table(struct tnode *AST) {
if(AST != NULL) {
print_table(AST->left);
printf("%s", AST->datum);
print_table(AST->right);
}
}但是,这会自上而下地打印树。例如,如果给定5 4 + 3 -,它将返回-3+45。我想让它打印的是5+4-3,本质上是打印最左边的子节点,然后是它的父节点,然后是那个父节点的右子节点,直到树的所有元素都被打印出来。我该怎么做呢?
发布于 2015-05-10 08:25:39
struct tnode*
build_tree(struct snode **S)
{
struct tnode* root;
if (*S == NULL)
return NULL;
char *top = peek(*S);
if (is_operator(top))
{
root = create_node(top);
pop(S);
root->right = build_tree(S);
pop(S);
root->left = build_tree(S);
return root;
}
root = create_node(top);
return root;
}我认为你的问题在于如何构建你的树。打印功能应该适用于您。这是一种构建树的方法。我在你的班上。如果你想见面,一起做这个项目,我很乐意。
https://stackoverflow.com/questions/30144516
复制相似问题