【数据结构】二叉树的层次遍历2

前端之家收集整理的这篇文章主要介绍了【数据结构】二叉树的层次遍历2前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. typedef char DataType;
  4. //树结点的数据类型定义
  5. typedef struct BTnode{
  6. DataType data;
  7. struct BTnode* lchild,*rchild;
  8. }BTree;
  9. //队列的结点数据类型定义
  10. typedef struct node{
  11. BTree * tdata; //存放树结点类型的指针
  12. struct node *next;
  13. }qnode;
  14. //队头指针 和 队尾指针
  15. typedef struct {
  16. qnode *front,*rear;
  17. }linkQueue;
  18. //初始化队列
  19. void Init(linkQueue *q)
  20. {
  21. q->front=q->rear=NULL;
  22. }
  23. //元素入队
  24. void InsertQueue(linkQueue * &q,BTree * e)
  25. {
  26. qnode * node;
  27. node=(qnode*)malloc(sizeof(qnode));
  28. node->tdata=e;
  29. node->next=NULL;
  30. if(NULL==q->front)
  31. {
  32. q->front=q->rear=node;
  33. }
  34. else
  35. {
  36. q->rear->next=node;
  37. q->rear=node;
  38. }
  39.  
  40. }
  41. //元素出队
  42. BTree * outQueue(linkQueue * &q)
  43. {
  44. BTree * e;
  45. qnode *temp;
  46. if(NULL==q->front)
  47. e=NULL;
  48. else
  49. {
  50. temp=q->front;
  51. e=temp->tdata;
  52. q->front=temp->next;
  53. free(temp);
  54. }
  55. return e;
  56. }
  57. //创建二叉树,以先序的方式输入,如果左孩子或右孩子为空,则输入#
  58. /*
  59. 例子 A 输入为:ABD##E##CF###
  60. / \
  61. B C
  62. / \ /
  63. D E F
  64. */
  65. void createBTree(BTree * &t)
  66. {
  67. char c;
  68. c=getchar();
  69. if(c=='#')
  70. t=NULL;
  71. else
  72. {
  73. t=(BTree*)malloc(sizeof(BTree));
  74. t->data=c;
  75. createBTree(t->lchild);//创建左子树
  76. createBTree(t->rchild);//创建右子树
  77. }
  78. }
  79.  
  80. /*
  81.  
  82. 二叉树的层次遍历算法:
  83. 1.队列queue初始化;
  84. 2. 将根指针入队;
  85. 3. 循环直到队列queue为空
  86. 3.1 q=队列queue出队的元素;
  87. 3.2 访问结点q的数据域;
  88. 3.3 若结点q存在左孩子,则将左孩子入队;
  89. 3.4 若结点q存在右孩子,则将右孩子入队;
  90.  
  91. */
  92. //二叉树的层次遍历
  93. void hierarchyTtraversal(linkQueue *queue,BTree * root)
  94. {
  95. BTree *q;
  96. InsertQueue(queue,root);
  97. while(NULL!=queue->front)
  98. {
  99. q=outQueue(queue);
  100. printf("%c ",q->data);
  101. if(q->lchild)
  102. InsertQueue(queue,q->lchild);
  103. if(q->rchild)
  104. InsertQueue(queue,q->rchild);
  105. }
  106. }
  107.  
  108. int main()
  109. {
  110. BTree *root;
  111. linkQueue queue;
  112. Init(&queue);
  113. createBTree(root);
  114. hierarchyTtraversal(&queue,root);
  115. printf("\n");
  116. return 0;
  117. }

猜你在找的数据结构相关文章