当前位置:网站首页>C语言实现树的底层遍历--超简代码
C语言实现树的底层遍历--超简代码
2022-08-03 06:34:00 【干饭小白】
//对树进行底层遍历时使用了队列的结构
基础类型:
typedef enum {FALSE = 0,TRUE = 1} Bool;
typedef enum {VOERFLOW = -2,UNDERFLOW = -1, ERROR = 0,OK = 1} Status;
树的二叉链表结点定义:
typedef struct Node{
char data;
struct Node *firstchild,*nextbrother;
}Node,*TreeNode;
//实现队列基本操作的函数原型表
void InitQueue(Queue *Q); //初始化队列
Bool IsEmpty(Queue Q); //判断队列是否为空,若是则返回TRUE,否则返回FALSE
void EnQueue(Queue *Q,TreeNode p); //元素入队列
void DeQueue(Queue *Q,TreeNode *p); //元素出队列
//函数代码
Status LevelTraverser(TreeNode root)
{
/*层序遍历树,树采用孩子-兄弟表示法,root是树根结点的指针*/
Queue tmpQ;
TreeNode ptr,brotherptr;
if( !root )
return ERROR;
InitQueue(&tmpQ);
EnQueue(tmpQ,root);
brotherptr = root->nextbrother;
while(brotherptr)
{
EnQueue(&tmpQ,brotherptr);
brotherptr=brotherptr->nextbrother;
}
while(!IsEmpty(tmpQ))
{
DeQueue(&tmpQ,&ptr);
printf("%c\t",ptr->data);
if(!ptr->firstchild) continue;
EnQueue(&tmpQ,ptr->firstchild);
brotherptr =ptr->brotherptr->nextbrother;
while(brotherptr)
{
EnQueue(&tmpQ,brotherptr);
brotherptr = brotherptr->nextbrother;
}
}
return OK;
}边栏推荐
猜你喜欢
随机推荐
在线开启gtid偶发hang住的问题解决
DIFM network, rounding and repetition
多线程可见
从学生到职场的转变
Laravel 中使用子查询
10 common data types in MySQL
最新版图书馆招聘考试常考试题重点事业单位
数据仓库指标体系实践
nacos-2.0.3启动报错出现no datasource set的坑
qt学习之旅--MinGW编译FFmpeg(32bit)
调用feign报错openfeign/feign-core/10.4.0/feign-core-10.4.0.jar
C语言实现通讯录功能(400行代码实现)
【RT_Thread学习笔记】---以太网LAN8720A Lwip ping 通网络
人脸检测和识别--face recognition包
torch.nn.modules.activation.ReLU is not a Module subclass
CISP-PTE Zhenti Demonstration
用代码构建UI界面
力扣解法汇总622-设计循环队列
Week5
【多线程进阶】--- 常见锁策略,CAS,synchronized底层工作原理,JUC,线程安全的集合类,死锁









