Posted on

Description

Submission

/**
 * 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) {
        if(!root) return {};
        vector<vector<int>> rets;
        queue<TreeNode*> q;
        q.push(root);

        while(!q.empty()) {
            int s = q.size();
            vector<int> row;

            while(s--) {
                TreeNode* node = q.front();
                q.pop();
                row.push_back(node->val);
                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
            }

            rets.push_back(row);
        }
        return rets;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *