二叉树的创建与遍历

本文详细介绍了如何使用前序和中序遍历结果来唯一确定并构建一棵二叉树,通过C++代码实现展示了二叉树的创建过程及先序、中序和后序遍历方法。

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

 

前序和中序、中序和后序都可以唯一确定一棵二叉树
前序和后序不可以唯一确定一棵二叉树

 

#include<iostream>
#include<stdlib.h>
#define maxSize 100
using namespace std;
typedef struct BTNode
{
	char data;
	struct BTNode *lchild;
	struct BTNode *rchild;
}BTNode;
void Visit(BTNode *p)//访问结点
{
	cout<<p->data;
}
void preorder(BTNode *p)//先序遍历 
{
	if(p!=NULL)
	{
		Visit(p);
		preorder(p->lchild);
		preorder(p->rchild);
	}
}
void inorder(BTNode *p)//中序遍历 
{
	if(p!=NULL)
	{
		inorder(p->lchild);
		Visit(p);
		inorder(p->rchild);
	}
}
void postorder(BTNode *p)//后序遍历 
{
	if(p!=NULL)
	{
		postorder(p->lchild);
		postorder(p->rchild);
		Visit(p);
	}
}
void CreateBiTree(BTNode *&T,string preorder,string inorder)
{
	if(preorder.length()==0)
	{
		T=NULL;
		return ;
	}
	char r=preorder[0];
	//根在中序序列中的位置
	int id=inorder.find(r);
	//左右孩子的中序序列
	string l_inorder=inorder.substr(0,id);
	string r_inorder=inorder.substr(id+1);
	//左右孩子的长度
	int l_length=l_inorder.length();
	int r_length=r_inorder.length();
	//左右孩子的前序序列
	string l_preorder=preorder.substr(1,l_length);
	string r_preorder=preorder.substr(1+l_length);
	T=(BTNode*)malloc(sizeof(BTNode));
   	if(T!=NULL)
    {
	   T->data=r;
	   //递归创建左右孩子
       CreateBiTree(T->lchild,l_preorder,l_inorder);
	   CreateBiTree(T->rchild,r_preorder,r_inorder);
    }
}
int main()
{
	//前序 和中序 、中序 和后序 都可唯一确定一棵二叉树 ,前和后不可以 
	string pre="ABCDEFGH";//先序 
	string in="CBEDFAHG";//中序 
	BTNode *T;
	CreateBiTree(T,pre,in);
	cout<<"先序遍历:"; preorder(T);  cout<<endl; 
	cout<<"中序遍历:";   inorder(T);   cout<<endl;
	cout<<"后续遍历:";   postorder(T); cout<<endl;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值