二叉树的遍历(递归):先序、中序、后序

这篇博客详细介绍了二叉树的先序、中序和后序遍历的递归算法,并探讨了如何统计叶子节点数目及计算二叉树高度的方法。此外,还讨论了非递归方式实现二叉树遍历的策略。

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

二叉树的遍历:先序、中序、后序

先序遍历的算法

  1. 先访问根结点
  2. 先序遍历左子树
  3. 先序遍历右子树
void PreOrder(BiTree root)
{
	if(root!=NULL)
	{
		printf("%c",root->data);
		PreOrder(root->lchild);
		PreOrder(root->rchild);
	}
} 

中序遍历的算法

  1. 中序遍历左子树
  2. 访问根结点
  3. 中序遍历右子树
void InOrder(BiTree root)
{
	if(root!=NULL)
	{
		InOrder(root->lchild);  //访问左子树
		printf("%c",root->data);  //访问根结点
		InOrder(root->rchild);   //访问右子树
	}
}

后序遍历的算法

  1. 后序遍历左子树
  2. 后序遍历右子树
  3. 访问根结点
void PostOrder(BiTree root)
{
	if(root!=NULL)
	{
		PostOrder(root->lchild);
		PostOrder(root->rchild);
		printf("%c",root->data);
	}
}

一、统计叶子结点数目

方法1:LeafCount为全局变量,在调用前初始化值为0

int LeafCount=0;
void LeafNum(BiTree root)
{
	if(root!=NULL)
	{
		if(root->lchild==NULL && root->rchild==NULL)
			LeafCount++;
		LeafNum(root->lchild);
		leafNum(root->rchild);
	}
}

方法2:采用函数返回值

int leaf(BiTree root)
{
	int LeafCount;
	if(root==NULL)
		LeafCount=0;
	else if((root->lchild==NULL) && (root->rchild==NULL))
		LeafCount=1;
	else
		LeafCount=leaf(root->lchild)+leaf(root->rchild);
	return LeafCount;
}

在这里插入图片描述

二、计算二叉树的高度

求二叉树的高度
方法1:

int depth=0;
void PreTreeDepth(BiTree root, int h)
{
	if(root!=NULL)
	{
		if(h>depth)
			depth=h;
		PreTreeDepth(root->lchild, h+1);
		PreTreeDepth(root->rchild, h+1);
	}
}

方法2:

int PostTreeDepth(BiTree root)
{
	int hl, hr, max;
	if(root!=NULL)
	{
		hl=PostTreeDepth(root->lchild);
		hr=PostTreeDepth(root->rchild);
		max=hl>hr?hl:hr;
		return max+1;
	}
	else
		return 0;
}

三、二叉树的非递归遍历

中序遍历的非递归算法

void InOrder(BiTree root)
{
	SqStack S;
	InitStack(S);
	BiNode *P;
	p=root;
	while(p || !StackEmpty(S))
	{
		if(p)
		{
			Push(S,p);  //保存根结点
			p=p->lchild;  //遍历左子树
		}
		else
		{
			Pop(S,p);    //弹出根结点
			visit(p->data);   //访问根结点
			p=p->rchild;   //遍历右子树
		}
	}
}

先序遍历的非递归算法

void PreOrder(BiTree root)
{
	SqStack S;
	InitStack(S);
	BiNode *p;
	p=root;
	while(p || !StackEmpty(S))
	{
		if(p)
		{
			visit(p->data);
			Push(S,p);
			p=p->lchild;
		}
		else
		{
			Pop(S,p);
			p=p->rchild;
		}
	}
}

后序遍历的非递归算法

void PostOrder(BiTree root)
{
	BiTree p=root, r=NULL;
	SqStack S;
	InitStack(S);
	while(p || !StackEmpty(S))
	{
		if(p)
		{
			Push(S,p);
			p=p->lchild;
		}
		else
		{
			p=GetTop(S);
			if(p->rchild!=NULL && p->rchild != r) //右子树存在,且未被访问
				p=p->rchild;
			else
			{
				pop(S,p);
				visit(p->data);
				r=p;  //记录最近已经访问过的结点
				p=NULL:  //结点访问完后,重置p指针
			}
			
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值