本题代码如下
void btreetoexp(tree t, char deep)
{
if (t == NULL)
return;
else if (t->lchild == NULL && t->rchild == NULL)
printf("%c", t->data);//输出操作数,不加括号
else {
if (deep > 1)
printf("(");
btreetoexp(t->lchild, deep + 1);
printf("%c", t->data);
btreetoexp(t->rchild, deep + 1);
if (deep > 1)
printf(")");
}
}
完整测试代码
#include<stdio.h>
#include<stdlib.h>
typedef struct treenode {
char data;
struct treenode* lchild, * rchild;
}treenode, * tree;
void buildtree(tree* t)//建树
{
char ch;
ch = getchar();
if (ch == '#')
*t = NULL;
else
{
*t = (treenode*)malloc(sizeof(treenode));//分配空间
(*t)->data = ch;
(*t)->lchild = NULL;
(*t)->rchild = NULL;
buildtree(&((*t)->lchild));
buildtree(&((*t)->rchild));
}
}
void btreetoexp(tree t, char deep)
{
if (t == NULL)
return;
else if (t->lchild == NULL && t->rchild == NULL)
printf("%c", t->data);//输出操作数,不加括号
else {
if (deep > 1)
printf("(");
btreetoexp(t->lchild, deep + 1);
printf("%c", t->data);
btreetoexp(t->rchild, deep + 1);
if (deep > 1)
printf(")");
}
}
int main() {
tree t;
buildtree(&t);
btreetoexp(t, 1);//根的高度为1
return 0;
}
//*+a##b##*c##-#d##
/*
*
+ *
a b c -
d
*/