3 ms 15 lines C++, super easy and clean!!!


  • 0
    K
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> res;
            queue<TreeNode*> q;
            if(root) q.push(root);
            while (!q.empty()) {
                res.push_back(vector<int>());
                int size = q.size();
                for (int i = 0; i < size; ++i) {
                    auto temp = q.front();
                    res.back().push_back(temp->val);
                    q.pop();
                    if (temp->left)  q.push(temp->left);
                    if (temp->right)  q.push(temp->right);                
                }
            }
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.