先序中序-得后序

代码:

#include<stdio.h> 
#include<stdlib.h>
#include<string.h>
#define N 100
typedef struct bitnode
{
	char data;
	struct bitnode *lchild,*rchild;
}bitnode,*bitree;
bitnode* createpre(char *pre,char *in,int n) 
{
	int i;
	int n1=0,n2=0;
	int m1=0,m2=0;
	bitnode *node=NULL;
	char lpre[N],rpre[N];
	char lin[N],rin[N];
	if(n==0)
	return NULL;
	node=(bitnode*)malloc(sizeof(bitnode));
	if(node==NULL)
	return NULL;
	node->data=pre[0];	
	for(i=0;i<n;i++)
	{
		if((i<=n1)&&(in[i]!=pre[0]))
		lin[n1++]=in[i];
		else if(in[i]!=pre[0])
		rin[n2++]=in[i];
	}
	for(i=1;i<n;i++)
	{
		if(i<(n1+1))
		lpre[m1++]=pre[i];
		else
		rpre[m2++]=pre[i];
	}
	node->lchild=createpre(lpre,lin,n1);
	node->rchild=createpre(rpre,rin,n2);
	return node;
}
void postorder(bitree root)
{
	if(root)
	{
	postorder(root->lchild);
	postorder(root->rchild);
	printf("%c",root->data);		
	}
}
int main()
{
	char renode[N];
	char innode[N];
	int n=0;
	char ch;
	bitree root=NULL;
	printf("请输入先序序列:\n"); 
	    while((ch=getchar())&&ch!='\n')
	renode[n++]=ch;
	n=0;
	printf("请输入中序序列:\n");	
	while((ch=getchar())&&ch!='\n')
	innode[n++]=ch;
	root=createpre(renode,innode,n);
    printf("该二叉树的后序序列:\n"); 
	postorder(root);
	return 0;
}

图片:

猜你喜欢

转载自blog.csdn.net/Tjhfsghbjknjdy/article/details/85012643