0
点赞
收藏
分享

微信扫一扫

二叉树层序遍历

mafa1993 2022-02-27 阅读 71

题目描述:

在这里插入图片描述
输入

输出

解题思路:
1.利用vector<vector>
2.第一层vector:每一层数据个数
第二层vector:每一层数据

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*> q;
        int levelSize = 0;
        if(root)
        {
            q.push(root);
            levelSize = 1;
        }
        vector<vector<int>> vv;
        while(!q.empty())
        {
            //控制着,一层一层出
            vector<int> v;
            for(int i = 0; i < levelSize; i++)
            {
                TreeNode* front = q.front();
                q.pop();
                v.push_back(front->val);  //每一层的数据个数
                //左孩子进队列
                if(front->left)
                {
                    q.push(front->left);
                }
                //右孩子进队列
                if(front->right)
                {
                    q.push(front->right);
                }
            }
            //上一层出完了,下层也都入队列,队列的size为下一层的数据个数
            levelSize = q.size();
            vv.push_back(v);
        }
        return vv;
    }
};
举报

相关推荐

0 条评论