lesson19-3 以孩子兄弟链表为存储结构,请设计递归和非递归算法求树的深度

这篇博客探讨如何利用孩子兄弟链表存储结构,设计递归和非递归算法来求解树的深度。通过将firstchild映射为lchild,nextsibling映射为rchild,可以将操作转化为类似二叉树的方式。文中提供了相应的代码实现,并进行了测试验证。
部署运行你感兴趣的模型镜像

思路:

firstchild对应lchild

nextsibling对应rchild

其他操作和普通二叉树的操作一样

代码:

int getHeight(BTNode *t){//递归算法
	if(!t)
		return 0;
	int hc=getHeight(t->firstchild);
	int hs=getHeight(t->nextsibling);
	return (hc+1)>hs?hc+1:hs;
}

int getHeight_(BTNode *t){//非递归算法,层次遍历思想
	BTNode *que[MAXSIZE];
	int front=-1,rear=-1;
	int level=0,last=0;
	rear=(rear+1)%MAXSIZE;
	que[rear]=t;
	BTNode *p;
	while(front!=rear){
		front=(front+1)%MAXSIZE;
		p=que[front];
		if(p->firstchild){
			rear=(rear+1)%MAXSIZE;
			que[rear]=p->firstchild;
		}
		if(p->nextsibling){
			rear=(rear+1)%MAXSIZE;
			que[rear]=p->nextsibling;
		}
		if(front==last){//最右结点出队
			level++;
			last=rear;//当这一层结点都入队后,把rear赋值给last
		}
	}
	return level;
}

测试:

#include<stdio.h>
#include <stdlib.h>
#include<math.h>	//数学函数,求平方根、三角函数、对数函数、指数函数...
 
#define MAXSIZE 100
 
//用于使用c++的输出语句
#include<iostream>
using namespace std;

typedef struct BTNode    
{
	char data;
	struct BTNode *firstchild;
	struct BTNode *nextsibling;
}BTNode;

void createBiTree(BTNode* &T);
int getHeight(BTNode *t);
int getHeight_(BTNode *t);

void main(){
	BTNode *t;
	createBiTree(t);

	cout<<endl;
	cout<<getHeight(t)<<endl;
	cout<<getHeight_(t)<<endl;
}

int getHeight(BTNode *t){//递归算法
	if(!t)
		return 0;
	int hc=getHeight(t->firstchild);
	int hs=getHeight(t->nextsibling);
	return (hc+1)>hs?hc+1:hs;
}

int getHeight_(BTNode *t){//非递归算法,层次遍历思想
	BTNode *que[MAXSIZE];
	int front=-1,rear=-1;
	int level=0,last=0;
	rear=(rear+1)%MAXSIZE;
	que[rear]=t;
	BTNode *p;
	while(front!=rear){
		front=(front+1)%MAXSIZE;
		p=que[front];
		if(p->firstchild){
			rear=(rear+1)%MAXSIZE;
			que[rear]=p->firstchild;
		}
		if(p->nextsibling){
			rear=(rear+1)%MAXSIZE;
			que[rear]=p->nextsibling;
		}
		if(front==last){//最右结点出队
			level++;
			last=rear;//当这一层结点都入队后,把rear赋值给last
		}
	}
	return level;
}

void createBiTree(BTNode* &T)
{
	char  ch;
	cin>>ch;
	if(ch=='#') T=NULL;
	else
	{
		T=(BTNode *)malloc(sizeof(BTNode));
		T->data=ch;
		cout<<"put in \'"<<T->data<<"\' lchild"<<endl;
		createBiTree(T->firstchild);
		cout<<"put in \'"<<T->data<<"\' rchild"<<endl;
		createBiTree(T->nextsibling);
	}
}

 

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值