Chinaunix首页 | 论坛 | 博客
  • 博客访问: 136110
  • 博文数量: 38
  • 博客积分: 306
  • 博客等级: 二等列兵
  • 技术积分: 335
  • 用 户 组: 普通用户
  • 注册时间: 2012-10-29 15:19
文章分类

全部博文(38)

文章存档

2013年(23)

2012年(15)

我的朋友

分类: C/C++

2013-08-23 11:22:24

利用队列实现二叉树层次遍历

层次遍历用队列实现,不用递归方法,一边入队一边出队,终止条件是队列为空。
  1. #include   
  2. #include   
  3. #include   
  4. #include   
  5. #include   
  6. #include   
  7. using namespace std;  
  8.   
  9. typedef struct BiTNode{  
  10.     char data;  
  11.     BiTNode *lchild, *rchild;  
  12. }BiTNode,*BiTree;  
  13.   
  14. void CreateBiTree(BiTree &T)//建树  
  15. {  
  16.     char ch;  
  17.     scanf("%c",&ch);  
  18.     if(ch==' ')  
  19.     {  
  20.         T=NULL;  
  21.         return;  
  22.     }  
  23.     else  
  24.     {  
  25.         T=(BiTree)malloc(sizeof(BiTNode));  
  26.         if(!T)  
  27.             exit(1);  
  28.         T->data=ch;  
  29.         CreateBiTree(T->lchild);  
  30.         CreateBiTree(T->rchild);  
  31.     }  
  32. }  
  33. void LevelOrderTraverse(BiTree T)//层次遍历  
  34. {  
  35.     queue Queue;  
  36.     if(!T)  
  37.     {  
  38.         printf("空树!\n");  
  39.         return;  
  40.     }  
  41.     Queue.enqueue(T);  
  42.     while(!Queue.empty())  
  43.     {  
  44.         T=Queue.front();  
  45.         Queue.dequeue();  
  46.         printf("%c",T->data);  
  47.         if(T->lchild)  
  48.             Queue.enqueue(T->lchild);  
  49.         if(T->rchild)  
  50.             Queue.enqueue(T->rchild);         
  51.     }  
  52. }  
  53. void main()  
  54. {  
  55.     
  56.     BiTree T;  
  57.     CreateBiTree(T);  
  58.     LevelOrderTraverse(T);  
  59.     printf("\n");  
  60. }  
阅读(1510) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~