数据结构与算法之由遍历构造二叉树

李春葆系列

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#define MaxSize  100
using namespace std;
typedef  char ElemType ;
typedef struct node
{
	ElemType data;
	struct node * lchild;
	struct node * rchild;
}BTNode;

void DestroyBTree(BTNode *& b)//销毁二叉树 
{
	if(b!=NULL)
	{
		DestroyBTree(b->lchild);
		DestroyBTree(b->rchild);
		free(b);
	}
 } 
 
 

BTNode *CreatBT1(char *pre,char * in,int n)//先序加中序构造二叉树 
{
	BTNode *b;
	char *p;
	int k;
	if(n<=0)
	{
		return NULL;
	}
	b=(BTNode*)malloc(sizeof(BTNode));
	b->data=*pre;
	for(p=in;p<in+n;p++)
	{
		if(*p==*pre)
		{
			break;
		}
	 } 
    k=p-in;
    b->lchild=CreatBT1(pre+1,in,k);
    b->rchild=CreatBT1(pre+k+1,p+1,n-k-1);
    return b;
}

BTNode *CreateBT2(char *post ,char *in,int n)//后序加中序构造二叉树 
{
	BTNode *b;
	char r;
	char *p;
	int k;
	if(n<=0)
	{
		return NULL;
	}
	r=*(post+n-1);
	b=(BTNode *)malloc(sizeof(BTNode));
	b->data=r;
	for(p=in;p<in+n;p++){
		if(*p==r)
		{
			break;
		}
	}
	k=p-in;
	b->lchild=CreateBT2(post,in,k);
	b->rchild=CreateBT2(post+k,p+1,n-k-1);
	return b;
}

BTNode *FindNode(BTNode * b,ElemType x)//查找结点 
{
	BTNode *p;
	if(b==NULL)
	{
		return NULL;
	}
	else if(b->data==x)
	{
		return b;
	}
	else
	{
		p=FindNode(b->lchild,x);
		if(p!=NULL)
		{
			return p;
		}
		else
		{
			return FindNode(b->rchild,x);
		}
	}
}
BTNode *LchildNode(BTNode *p)//返回结点p的左孩子结点 
{
	return p->lchild;
 } 
 
 
 BTNode *RchildNode(BTNode *p)//返回结点p的右孩子结点 
 {
 	return p->rchild;
 }
 
int BTHeight(BTNode *b)//求高度 
 {
 	if(b==NULL)
 	{
 		return (0);
	 }
	 else
	 {
	 	return (BTHeight(b->lchild)>BTHeight(b->rchild))?(BTHeight(b->lchild)+1):(BTHeight(b->rchild)+1);
	 }
 }
 
void DispBTree(BTNode *b)//输出二叉树 
{
	if(b!=NULL)
	{
		printf("%c",b->data);
		if(b->lchild!=NULL||b->rchild!=NULL)
		{
			printf("(");
			DispBTree(b->lchild);
			if(b->rchild!=NULL)
			{
				printf(",");
			}
			DispBTree(b->rchild);
			printf(")");
			
		}
	}
}

int main()
{   BTNode *b,*a,*p,*i;
    b=CreatBT1("ABDEHJKLMNCFGI","DBJHLKMNEAFCGI",14);//先序加中序构造二叉树 
    a=CreatBT1("DBJHLKMNEAFCGI","DJLNMKHEBFIGCA",14);//后序加中序构造二叉树 
	DispBTree(b);
	printf("\n");
	DispBTree(a);
	printf("\n");
    printf("树高:%d\n",BTHeight(b));
    printf("树高:%d\n",BTHeight(a));
    DestroyBTree(b);
    DestroyBTree(a);
    printf("二叉树a,b已经释放"); 
}
posted @ 2019-11-14 23:50  AmosAlbert  阅读(112)  评论(0编辑  收藏  举报