zl程序教程

您现在的位置是:首页 >  后端

当前栏目

剑指 Offer 32 - II. 从上到下打印二叉树 II

二叉树 打印 II Offer 32
2023-09-14 09:01:26 时间

题目链接

剑指 Offer 32 - II. 从上到下打印二叉树 II easy

题目描述

例如:
给定二叉树: [3,9,20,null,null,15,7]

在这里插入图片描述
返回其层次遍历结果:

[
[3],
[9,20],
[15,7]
]

提示:

  • 节点总数 <= 1000

解法:bfs

直接使用 bfs 层序遍历,把每一层的结点值都记录下来,最后存入答案 ans种即可。

时间复杂度: O ( n ) O(n) O(n)

C++代码:


class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        if(root == nullptr) return ans;
        
        queue<TreeNode*> q;
        q.push(root);

        while(!q.empty()){
            int sz = q.size();
            vector<int> temp;
            for(int i = 0;i < sz;i++){
                auto t = q.front();
                q.pop();

                temp.push_back(t->val);
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
            ans.push_back(temp);
        }
        return ans;
    }
};