102. 二叉树的层序遍历

102. 二叉树的层序遍历

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:

img

输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]

示例 2:

输入:root = [1]
输出:[[1]]

示例 3:

输入:root = []
输出:[]

提示:

  • 树中节点数目在范围 [0, 2000]
  • -1000 <= Node.val <= 1000

思路:

​ BFS广度优先遍历即可

class Solution {
public:

    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>>ans;
        if(root==nullptr)return ans;
        //BFS
        queue<TreeNode*>q;//BFS核心结构
        q.push(root);
        while(!q.empty()){//while控制从上到下
            int sz=q.size();
            vector<int>res;
            for(int i=0;i<sz;i++){//for从左到右
                TreeNode* cur=q.front();
                q.pop();
                res.push_back(cur->val);
                if(cur->left!=nullptr)q.push(cur->left);
                if(cur->right!=nullptr)q.push(cur->right);
            }
            ans.push_back(res);
        }
        return ans;
    }
};
posted @ 2022-05-28 09:33  BailanZ  阅读(16)  评论(0编辑  收藏  举报