二叉树的构建

本文介绍了三种构建二叉树的方法:1.基于先序遍历的结果创建;2.结合先序和中序遍历创建;3.使用中后序遍历创建。详细探讨了每种方法的步骤和思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、利用先序遍历的结果创建

1:

void CreateTree4(BtNode *&ptr,ElemType *&str)
{
	if(NULL == str || *str == '#')
	{
		ptr = NULL;
	}
	else
	{
		ptr = Buynode();
		ptr->data = *str;
		CreateTree4(ptr->leftchild,++str);
		CreateTree4(ptr->rightchild,++str);
	}
}

int main()
{
    char *str="ABC##DE##F##G#H##";
    BtNode *root = NULL;
    CreateTree4(root,str);

    return 0;
}

2:

BtNode * CreateTree1()
{
	BtNode *s = NULL;
	ElemType item;
	cin>>item;
	if(item != '#')
	{
		s = Buynode();
		s->data = item;
		s->leftchild = CreateTree1();
		s->rightchild = CreateTree1();
	}
	return s;
}
int main()
{
	BtNode *root = NULL;
	root = CreateTree1();
        return 0;
}

二、利用先序、中序遍历的结果创建二叉树:

int  FindPos(ElemType *is,ElemType x,int n)
{
	int pos = -1;
	for(int i = 0;i<n;++i)
	{
		if(x == is[i])
		{
			pos = i;
			break;
		}
	}
	return pos;
}

BtNode * CreatePI(ElemType *ps,ElemType *is,int n)  //前中序创建树
{
	BtNode *s = NULL;
	if(n > 0)
	{
		s = Buynode();
		s->data = ps[0];// s->data = *ps;
		int pos = FindPos(is,ps[0],n);
		if(pos == -1) exit(1);
		s->leftchild = CreatePI(ps+1,is,pos);
		s->rightchild = CreatePI(ps+1+pos,is+1+pos,n - pos - 1);
	}
	return s;
}

BtNode * CreateTreePI(ElemType *ps,ElemType *is,int n)  //前中序创建树
{
	if(NULL == ps || NULL == is || n < 1)
		return NULL;
	else
		return CreatePI(ps,is,n);
}

int main()
{
	char *ps = "ABCDEFGH";
	char *is = "CBEDFAGH";
	char *ls = "CEFDBHGA";
	int n = strlen(ps); // n = sizeof(ps);//
	BtNode *root = NULL;
	root = CreateTreePI(ps,is,n);
	return 0;
}

三、利用中后序遍历创建二叉树

int  FindPos(ElemType *is,ElemType x,int n)
{
	int pos = -1;
	for(int i = 0;i<n;++i)
	{
		if(x == is[i])
		{
			pos = i;
			break;
		}
	}
	return pos;
}

BtNode * CreateIL(ElemType *is,ElemType *ls,int n)  //中后序创建树
{
	BtNode *s = NULL;
	if(n > 0)
	{
		s = Buynode();
		s->data = ls[n-1];
		int pos = FindPos(is,ls[n-1],n);
		if(pos == -1) exit(1);
		s->leftchild = CreateIL(is,ls,pos);
		s->rightchild = CreateIL(is+pos+1,ls+pos,n - pos - 1);
	}
	return s;
}

BtNode * CreateTreeIL(ElemType *is,ElemType *ls,int n)//中后序创建树
{
	if(NULL == is || NULL == ls || n < 1) 
		return NULL;
	else
		return CreateIL(is,ls,n);
}

int main()
{
	char *ps = "ABCDEFGH";
	char *is = "CBEDFAGH";
	char *ls = "CEFDBHGA";
	int n = strlen(ps); // n = sizeof(ps);//
	BtNode* root = NULL;
	
	root = CreateTreeIL(is,ls,n);  //中后序
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值