二叉树的各种实现

本文详细介绍了二叉树的基本操作,包括二叉树的声明与建立、遍历方法(先序、中序、后序及层序遍历)、求深度等,并提供了递归与非递归实现方式。

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

1.声明及建立

typedef struct BiTNode{
	char data;
	struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

int node,leafnode,depth;

void CreateBiTree(BiTree &T)//先序建立二叉树
{
	char ch;
	scanf("%c",&ch);
	if(ch=='#') T=NULL;
	else
	{
		if(!(T=(BiTNode *)malloc(sizeof(BiTNode)))) exit(-1);
		T->data=ch;
		CreateBiTree(T->lchild);
		CreateBiTree(T->rchild);
	}
}

2.遍历

A 中序遍历

1)递归方法(先序、后序改变一下VistElem()函数的位置即可)

int InOrderTraverse(BiTree T)//
{
	if(T)
	{
		if(InOrderTraverse(T->lchild))//先遍历左子树
			if(VistElem(T->data))//访问根结点
				if(InOrderTraverse(T->rchild)) return 1;//再遍历右子树 
				
				return -1;
	}
	return 1;
}
2)非递归实现

int InOrderFRE(BiTree T)//中序非递归1
{
	stack<BiTree>s1;
	BiTree t;
	s1.push(T);
	while(!s1.empty())
	{
		t=s1.top();
		while(t) 
		{t=t->lchild;s1.push(t);}
		s1.pop();//空指针退栈
		if(!s1.empty())
		{
			t=s1.top();
			s1.pop();
			if(!VistElem(t->data)) return -1;
			s1.push(t->rchild);
		}
	}
	return 1;
}

int InOrderFRE2(BiTree T)//中序非递归2
{
	stack<BiTree>s2;
	BiTree p=T;
	while(p||!s2.empty())
	{
		if(p) {s2.push(p);p=p->lchild;}
		else
		{
			p=s2.top();
			s2.pop();//根指针退栈
			
			if(!VistElem(p->data)) return -1;
			p=p->rchild;
		}
	}	
	return 1;
}

注意两种非递归方法的不同

3)层序遍历

int LevelOrderTraverse(BiTree T)//层序遍历
{
	queue<BiTree>q1;
	if(T) 
	{
		q1.push(T);
		while(!q1.empty())
		{
			BiTree t=q1.front();
			q1.pop();
			VistElem(t->data);
			if(t->lchild) q1.push(t->lchild);
			if(t->rchild) q1.push(t->rchild);
		}
	}
	return 1;
}


3.求深度

int Depth(BiTree T)
{
	int ldepth,rdepth;
	if(T)
	{
		ldepth=Depth(T->lchild);
		rdepth=Depth(T->rchild);
	}
	else return 0;//空树返回0
	return ldepth>rdepth?ldepth+1:rdepth+1;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值