数据结构 树 层次遍历二叉树 C语言版
2017-08-27 17:18
351 查看
//层次遍历二叉树并输出结点的算法 #include <stdio.h> #include <stdlib.h> typedef struct NNode { char data; struct NNode *LChild; struct NNode *RChild; } BiTNode,*BiTree; //定义二叉树结点和结点指针 typedef BiTree QueueElementType; typedef struct Node { QueueElementType data; struct Node *next; } LinkQueueNode; //定义队列结点 typedef struct { LinkQueueNode *front; //队列头结点指针 LinkQueueNode *rear; //队列尾结点指针 } LinkQueue; //定义队列 int InitQueue(LinkQueue *Q ) //初始化队列 { Q->front=(LinkQueueNode * )malloc(sizeof(LinkQueueNode)); if(Q->front != NULL) { Q->rear=Q->front; Q->front->next=NULL; return 1; } else return 0;//溢出 } int EnterQueue(LinkQueue *Q,QueueElementType x) //元素x入链队列 尾插法 { LinkQueueNode * newnode; newnode=(LinkQueueNode *) malloc(sizeof(LinkQueueNode)); if(newnode != NULL) { newnode->data=x; newnode->next=NULL; Q->rear->next=newnode; Q->rear=newnode; return 1; } else return 0; } int DeleteQueue(LinkQueue *Q,QueueElementType *x ) //链队列出队 从开始的头开始取 { LinkQueueNode *p; if(Q->front==Q->rear) return 0; p=Q->front->next; Q->front->next=p->next; if(Q->rear==p ) Q->rear=Q->front; //如果去掉结点p后,队列为空 不要忘记将队列置空 *x=p->data; free(p); return 1; } int IsEmpty(LinkQueue *Q) //队列为空返回1 不为空返回0 { if(Q->front==Q->rear ) return 1; else return 0; } void CreateBiTree(BiTree *bt) //用先序遍历创建二叉树 { char ch; ch=getchar(); if(ch=='.') (*bt)=NULL; else { *bt=(BiTree)malloc(sizeof(BiTNode)); (*bt)->data=ch; CreateBiTree(&((*bt)->LChild)); CreateBiTree(&((*bt)->RChild)); } } void PreOrder(BiTree root) //先序遍历二叉树 { if(root!=NULL) { printf("%c",root->data); PreOrder(root->LChild); PreOrder(root->RChild); } } int LayerOrder(BiTree bt) //层次遍历二叉树 成功遍历返回1 失败返回0 { LinkQueue Q; BiTree p; InitQueue(&Q); if(bt==NULL) return 0; EnterQueue(&Q,bt); while(!IsEmpty(&Q)) { if(DeleteQueue(&Q,&p)); printf("%c ",p->data); if(p->LChild) EnterQueue(&Q,p->LChild); if(p->RChild) EnterQueue(&Q,p->RChild); } return 1; } int main() { BiTree bt; printf("用先序遍历创建二叉树 请输入树的内容 形式如AB..CD...的格式\n") ; CreateBiTree(&bt); PreOrder(bt); printf("\n"); if(LayerOrder(bt)) printf("层次遍历成功\n"); else printf("层次遍历失败\n"); return 0; }
相关文章推荐
- 数据结构和算法--二叉树的层次遍历
- 数据结构:二叉树(前,中,后,层次)非递归遍历。
- 数据结构-层次遍历二叉树
- 2015年大二上-数据结构-树和二叉树-2-(1)二叉树的层次遍历
- 数据结构:二叉树(前,中,后,层次)非递归遍历。
- 数据结构二叉树的前序中序后序层次遍历简单版,手写
- 数据结构 学习笔记(四):树(上):树的表示,二分查找,二叉树,先中后层次遍历
- 数据结构,二叉树已知后续中序,建树,层次遍历;
- 数据结构 — 5.二叉树层次遍历
- 数据结构--二叉树--层次遍历二叉树(顺序遍历)
- 二叉树各种相关操作(建立二叉树、前序、中序、后序、求二叉树的深度、查找二叉树节点,层次遍历二叉树等)(C语言版)
- 数据结构 第12讲 二叉树的层次遍历
- 数据结构学习笔记(8)---二叉树的层次遍历
- 数据结构学习——二叉树的层次遍历:上下左右&下上右左
- 数据结构--二叉树--层次遍历二叉树(链式遍历--队列)
- 数据结构—树和二叉树-2.二叉树的层次遍历(BFS)
- 采用队列数据结构按层次遍历二叉树
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 一步一步复习数据结构和算法基础-层次建立层次遍历二叉树