码迷,mamicode.com
首页 > 其他好文 > 详细

层次遍历

时间:2015-04-14 09:43:44      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 
  4 #define YES 1
  5 #define NO  2
  6 
  7 typedef struct node
  8 {
  9     
 10     char data;
 11     
 12     struct node* Lchild;
 13     struct node* Rchild;
 14     
 15 }BiTNode,*BiTree;//二叉树节点
 16 
 17 typedef struct qnode
 18 {
 19     
 20     BiTree data;
 21     
 22     struct qnode* next;
 23     
 24 }QueNode,*Queue;//队列的节点
 25 
 26 Queue CreateQNode(BiTree x)//创建队列的一个节点
 27 {
 28     
 29     Queue pointer=(Queue)malloc(sizeof(QueNode));
 30     
 31     pointer->next=NULL;
 32     pointer->data=x;
 33     
 34     return pointer;
 35     
 36 }
 37 
 38 void QuePop(Queue &q)//删除队首
 39 {
 40     
 41     Queue p=q;
 42     
 43     q=q->next;
 44     
 45     free(p);
 46     
 47 }
 48 
 49 BiTree CreateBiTNode(char x)//创建二叉树队列
 50 {
 51     
 52     BiTree pointer=(BiTree)malloc(sizeof(BiTNode));
 53     
 54     pointer->data=x;
 55     
 56     pointer->Lchild=NULL;
 57     pointer->Rchild=NULL;
 58     
 59     return pointer;
 60     
 61 }
 62 
 63 void PreOrderCreBiT(BiTree &root)//先序创建二叉树
 64 {
 65     
 66     char x=getchar();
 67     
 68     if(x==#) return;
 69     
 70     root=CreateBiTNode(x);
 71     
 72     PreOrderCreBiT(root->Lchild);
 73     PreOrderCreBiT(root->Rchild);
 74     
 75 }
 76 
 77 void LeverOrderTravel(BiTree root)//层次便利二叉树
 78 {
 79     
 80     Queue head,tail;
 81     
 82     if(root==NULL) return;
 83     
 84     head=tail=CreateQNode(root);
 85     
 86     while(head){
 87         
 88         if(head->data->Lchild)
 89             {
 90             
 91             tail->next=CreateQNode(head->data->Lchild);
 92             tail=tail->next;
 93             
 94             }
 95         
 96         if(head->data->Rchild) 
 97         {
 98             
 99             tail->next=CreateQNode(head->data->Rchild);
100             tail=tail->next;
101             
102         }
103         
104         printf("%c",head->data->data);
105         
106         QuePop(head);
107         
108     }
109     
110 }
111 
112 int main()
113 {
114     
115     BiTree root;
116     
117     PreOrderCreBiT(root);
118 
119     LeverOrderTravel(root);
120     
121     return 0;
122     
123 }

 

层次遍历

标签:

原文地址:http://www.cnblogs.com/yanglingwell/p/4423955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!