102. 二叉树的层序遍历

题目链接

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if (!root) return res;
        queue<TreeNode*> que;
        que.push(root);
        while (!que.empty()) {
            TreeNode* node;
            
            int size = que.size();
            vector<int> subres;
            
            for (int i = 0; i < size; i++) {
                    node = que.front();
                    que.pop();
                    subres.push_back(node->val);
                    if (node->left) que.push(node->left);
                    if (node->right) que.push(node->right);
            }

            res.push_back(subres);
            
        }
        return res;
    }
};

102. 二叉树的层序遍历_第1张图片

你可能感兴趣的:(leetcode,二叉树,leetcode)