二叉树的层次遍历

二叉树的层次遍历
  层次遍历,就是从上到下一层一层的遍历 。其实主要就是要借助一个队列的先进先出,去遍历
例如:

                           1

                 2                  3

         4          5           6            7

    8    9   10  11    12   13    14   15

 

代码实现

 1 void BinaryTreeLevelOrder(BTNode* root)
 2 {
 3     Queue q;
 4     //树为空,直接返回
 5     if (root == NULL)
 6     {
 7         return;
 8     }
 9     QueueInit(&q);
10     //先将根节点入队
11     QueuePush(&q, root);
12     while (QueueEmpty(&q))
13     {
14         //出队保存队头并访问
15         BTNode* front = QueueFront(&q);
16         printf("%c", front->_data);
17         QueuePop(&q);
18         //将出队结点的左子树根入队
19         if (front->_left)
20             QueuePush(&q, front->_left);
21         //将出队结点的右子树根入队
22         if (front->_right)
23             QueuePush(&q, front->_right);
24     }
25 }

 

posted @ 2019-04-11 09:57  linghu_java  阅读(872)  评论(0编辑  收藏  举报