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

题目1

题目链接

在这里插入图片描述
本题与层序遍历不同的是,是一层一层的输出。
难点:如何一层一层的输出(需要知道每层的个数)

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

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,最后输出数组翻转了一下。

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;
    }
};
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值