已知二叉树的先序(前序)遍历及中序遍历,还原该二叉树并输出其后续遍历
#include
#include
typedef char datatype;
typedef struct node
{
datatype data;
struct node *lchild,*rchild;
} bintnode,*bintree;
//后序遍历输出当前二叉树
void postorder(bintree root)
{
if(root==NULL)return;
else
{
postorder(root->lchild);
postorder(root->rchild);
printf("%c",root->data);
}
}
bintree buildBintree(char *pre,char *mid,int length)
{
int divlen=0;//左子树的长度
char *temp;
if(length<=0)return NULL;
bintree root=(bintree)malloc(sizeof(bintnode));
root->data=*pre;
temp=mid;//定义一个临时变量来存放中序遍历的序列
while(*temp!=*pre&&temp!=NULL)//当找到时以该点为分割点,前面记录下长度为当前节点下的左子树
{
divlen++;
temp++;
};
root->lchild=buildBintree(pre+1,mid,divlen);//递归得出左子树
root->rchild=buildBintree(pre+divlen+1,temp+1,length-divlen-1);//得出右子树
return root;
}
int main()
{
bintree root;
char pre[100],mid[100];
puts("请输入前序序列:");
gets(pre);
puts("请输入后续序列:");
gets(mid);
root=buildBintree(pre,mid,strlen(pre));
puts("后续序列是:");
postorder(root);
return 0;
}