层次遍历
2016-03-24 20:41
309 查看
#include<stdio.h> #include<malloc.h> #include<stdlib.h> //二叉树节点 typedef struct BitNode{ int data; struct BitNode *lchild; struct BitNode *rchild; }BitNode; BitNode *CreateBitBitNode(void) { BitNode *bt; int x; scanf("%d",&x); if(x==-1)bt=NULL; else{ bt = (BitNode *)malloc(sizeof(BitNode)); bt->data = x; bt->lchild = CreateBitBitNode(); bt->rchild = CreateBitBitNode(); } return bt; } //队列 typedef struct queue{ struct node *pFront; struct node *pBehind; int size; }Queue; //普通节点 typedef struct node{ struct BitNode * data; struct node * next; }Node; //队列初始化 Queue * init(){ Queue * pQueue = (Queue *)malloc(sizeof(Queue)); if(pQueue == NULL){ printf("init queue failed!\n"); exit(0); } pQueue->pFront = NULL; pQueue->pBehind = NULL; pQueue->size = 0; return pQueue; } //判断队列是否为空 int empty(Queue * pQueue){ if(pQueue->size == 0){ return 1; } return 0; } //队列中添加数据 void in(Queue * pQueue, BitNode * pBitNode){ Node * pNode = (Node *)malloc(sizeof(Node)); if(pNode == NULL){ printf("queue in data failed\n"); exit(0); } pNode->data = pBitNode; pNode->next = NULL; if(empty(pQueue)){ pQueue->pFront = pNode; }else{ pQueue->pBehind->next = pNode; } pQueue->pBehind = pNode; pQueue->size += 1; } //队列中移除并返回数据 BitNode * out(Queue * pQueue){ if(empty(pQueue)){ printf("queue is empty\n"); exit(0); } Node * pNode = pQueue->pFront; pQueue->pFront = pNode->next; pQueue->size -= 1; BitNode * pBitNode = pNode->data; free(pNode) ; pNode = NULL; return pBitNode; } BitNode * pop(Queue * pQueue){ if(empty(pQueue)){ printf("queue is empty!\n"); exit(0); } BitNode * pNode = pQueue->pBehind->data; return pNode; } //二叉树按层排印 void printLevel(BitNode * pRoot){ if(pRoot == NULL){ printf("binary BitNode is empty\n"); exit(0); } BitNode * pBitNode; Queue * pQueue = init(); in(pQueue, pRoot); while(!empty(pQueue)){ pBitNode = out(pQueue); printf("%d\n", pBitNode->data); if(pBitNode->lchild != NULL){ in(pQueue, pBitNode->lchild); } if(pBitNode->rchild != NULL){ in(pQueue, pBitNode->rchild); } } } int main(){ BitNode * pRoot = NULL; pRoot = CreateBitBitNode(); printLevel(pRoot); return 0; }
相关文章推荐
- Python引用复制,参数传递,弱引用与垃圾回收
- ccf 201512-3 画图
- 表达式求值(四则运算) 后序法
- Struts2+Spring+Hibernat整合
- TCP协议中的三次握手和四次挥手(图解)
- x264_param_default_preset()源码分析
- document.getElementById(), getElementsByname(),getElementsByClassName(),getElementsByTagName()
- 函数名称修饰符__cdelcl __fastcall 与__stdcall
- 网易面试总结
- Problem C: 顺序表基本运算(线性表)
- nyoj--300 Kiki & Little Kiki 2(矩阵快速幂)
- Problem P
- 第四周项目3-随机函数应用于游戏(2)小学生算数能力测试系统
- POJ 3061 Subsequence【尺取法】
- x264_param_default()源码分析;
- Oracle学习(一)
- cs231n Lecture 5
- 未在本地计算机上注册“Microsoft.ACE.OleDb.12.0”提供程序
- 作业五:分析system_call中断处理过程
- <c:forEach items="${revertList}" varStatus="reverts" var="revert" > <dl >