zoukankan      html  css  js  c++  java
  • 二叉树的层次遍历

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

                               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 }
  • 相关阅读:
    重载小于号
    无聊的会议
    程序内存和时间
    对拍
    读入和输出优化
    codevs 3269 混合背包
    清北第三套题
    codevs 2188 最长上升子序列
    清北第二套题
    [COGS896] 圈奶牛
  • 原文地址:https://www.cnblogs.com/linghu-java/p/10687831.html
Copyright © 2011-2022 走看看