当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
随机推荐
spark中的cache和checkpoint
信息学奥赛一本通T1454:山峰和山谷
spark中Repartition 和 Coalesce 区别
【卫朋】硬件创业:营销与开发同行
亿流量大考(1):日增上亿数据,把MySQL直接搞宕机了...
【第1天】SQL快速入门-基础查询(SQL 小虚竹)
mysql or语句的优化
Example of embedding code for continuous features
Sqoop 导入导出 Null 存储一致性问题
线程基础(二)
Oracle Rac 集群文件目录迁移
数仓埋点体系与归因实践
信息学奥赛一本通T1450:Knight Moves
CISP-PTE Zhenti Demonstration
帆软11版本参数联动为null查询全部
Data warehouse buried point system and attribution practice
华为设备配置BFD单跳检测二层链路
1066 Root of AVL Tree // AVL平衡二叉搜索树模板
IEEE RAL投初稿
Chrome configuration samesite=none method