LeCode:(102. 二叉树的层序遍历;107. 二叉树的层序遍历 II)

题目1

题目链接

本题与层序遍历不同的是,是一层一层的输出。

难点:如何一层一层的输出(需要知道每层的个数)

解题思路:
第一层只有一个结点,我们可以使用count计数,记录每层有几个结点,记录第二层有几个结点。然后根据第二层count计数,记录第三层有几个结点。直到遍历完。

cpp 复制代码
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        //根入,遍历,count++
        vector<vector<int>> outPut;  //输出的总数组
        vector<int> t;    //每层的小数组
        queue<TreeNode*> cur;   //队列用来记录层序遍历的结点
        int count = 1; //记录本层个数,第一层为1
        if(root == nullptr)  //树为空,直接返回大数组
        {
            return outPut;
        }
        cur.push(root);   //先将根入队
        while(!cur.empty())  //队列为空,遍历完毕
        {
            int k = count;   //把本层个数给k,
            count = 0;       //count清0, 接着记录下一层
            while(k--)
            {
                TreeNode* tem = cur.front();  
                cur.pop();        
                t.push_back(tem->val);  //将值给小数组
                if(tem->left)
                {
                    count++;
                    cur.push(tem->left);
                } 
                if(tem->right)
                {
                    count++;
                    cur.push(tem->right);
                }
            }
            outPut.push_back(t);   //一层遍历完
            t.clear();  //小数组清空
        }
        return outPut;
    }
};

题目2

题目链接

以为会有新思路,结果官方答案把题目1,最后输出数组翻转了一下。

cpp 复制代码
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {

        //根入,遍历,count++
        vector<vector<int>> outPut;  //输出的总数组
        vector<int> t;    //每层的小数组
        queue<TreeNode*> cur;   //队列用来记录层序遍历的结点
        int count = 1; //记录本层个数,第一层为1
        if(root == nullptr)  //树为空,直接返回大数组
        {
            return outPut;
        }
        cur.push(root);   //先将根入队
        while(!cur.empty())  //队列为空,遍历完毕
        {
            int k = count;   //把本层个数给k,
            count = 0;       //count清0, 接着记录下一层
            while(k--)
            {
                TreeNode* tem = cur.front();  
                cur.pop();        
                t.push_back(tem->val);  //将值给小数组
                if(tem->left)
                {
                    count++;
                    cur.push(tem->left);
                } 
                if(tem->right)
                {
                    count++;
                    cur.push(tem->right);
                }
            }
            outPut.push_back(t);   //一层遍历完
            t.clear();  //小数组清空
        }
        reverse(outPut.begin(),outPut.end());
        return outPut;
    }
};
相关推荐
stay_alive.4 分钟前
C++ 四种类型转换
开发语言·c++
卡提西亚9 分钟前
C++笔记-9-三目运算符和switch语句
c++·笔记
CodeWizard~30 分钟前
AtCoder Beginner Contest 430赛后补题
c++·算法·图论
大大dxy大大40 分钟前
机器学习-KNN算法示例
人工智能·算法·机器学习
喜欢吃燃面1 小时前
C++:哈希表
开发语言·c++·学习
mit6.8241 小时前
[C++] 时间处理库函数 | `tm`、`mktime` 和 `localtime`
开发语言·c++
SweetCode1 小时前
C++ 大数乘法
开发语言·c++
关于不上作者榜就原神启动那件事2 小时前
模拟算法乒乓球
开发语言·c++·算法
初圣魔门首席弟子2 小时前
C++ STL list 容器学习笔记:双向链表的 “小火车“ 操控指南
c++·windows·笔记·学习
Madison-No72 小时前
【C++】关于list的使用&&底层实现
数据结构·c++·stl·list·模拟实现