当前位置:网站首页>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;
}边栏推荐
猜你喜欢
随机推荐
(十四)51单片机——LCD1602实现滚动效果
华为设备配置BFD状态与接口状态联动
2022用户画像构建
第五章:指令集
word之图表目录中点号位置提升3磅
C语言入门实战(14):选择排序
El - tree set using setCheckedNodessetCheckedKeys default check nodes, and a new check through setChecked specified node
开放域OOD主要数据集、评价指标汇总
解读 refresh 十二步骤
DIFM network, rounding and repetition
PMP每日一练 | 考试不迷路-8.2(包含敏捷+多选)
帆软11版本参数联动为null查询全部
计算机网络常见面试题总结
tmp
MySQL - 触发器
关于NOI 2022的报到通知
qt学习之旅--MinGW编译FFmpeg(32bit)
华为设备配置BFD单跳检测二层链路
信息学奥赛一本通T1452:Keyboarding
keepalived安装部署









