数据结构——由前序与中序遍历确定的二叉树

由前序与中序遍历确定的二叉树

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define  MAXSIZE 50

typedef struct Node{        //二叉树的链式存储结点 
	char data;
	struct Node *Lchild;
	struct Node *Rchild;
}BiTNode,*BiTree;


void Visit(char data){
	printf("%c",data);
}

void PostOrder(BiTree T){    //后序递归遍历 
	if(T){
		PostOrder(T->Lchild);
		PostOrder(T->Rchild);
		Visit(T->data);
	}
} 

BiTree Construct(char *startPre,char *endPre,char *startIn,char *endIn){
	//先序遍历的第一个必然是根结点
	BiTree root=(BiTree)malloc(sizeof(BiTree));
	root->data=*startPre;
	root->Lchild=NULL;
	root->Rchild=NULL;
	
	
	//递归终止条件:先序遍历中只有一个结点
	if(startPre==endPre) return root;
	
	//在中序遍历中找到根结点
	char *rootIn=startIn;
	while(rootIn<=endIn&&(*rootIn)!=root->data)
		rootIn++;
		
	int leftlen=rootIn-startIn;//左子树的结点数
	if(leftlen>0)//左子树不为空,构造左子树
		root->Lchild=Construct(startPre+1,startPre+leftlen,startIn,rootIn-1);
	int rightlen=endIn-rootIn;//右子树的结点数
	if(rightlen>0)//右子树不为空,构造右子树
		root->Rchild=Construct(endPre-rightlen+1,endPre,rootIn+1,endIn);
	
	return root;
}


BiTree Create(char *pre,char *in,int len){
	if(pre==NULL || in==NULL || len<=0)   return NULL;
	
	return Construct(pre,pre+len-1,in,in+len-1); 
}


int main(){
	BiTree T;
	char Pre[MAXSIZE],In[MAXSIZE];
	int n; 
	for(int i=0;i<MAXSIZE;i++){
		Pre[i]='#';
		In[i]='#';
	}
	for(int j=0;j<MAXSIZE;j++){       //输入前序序列 
		Pre[j]=getchar();
		if(Pre[j]=='\n'){
			Pre[j]='#';
			n=j;
			break;
		}
	}
	for(int j=0;j<MAXSIZE;j++){      //输入中序序列 
		In[j]=getchar();
		if(In[j]=='\n'){
			In[j]='#';
			break;
		}	
	}
	 
	char *pre=Pre;//先序序列
	char *in=In;//中序序列
	T=Create(pre,in,n);

	PostOrder(T); 
	
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_41596568/article/details/84328084
今日推荐