Very simple C++ solution 8 ms


  • 0
    M
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> answer;
        if (root == 0) {
            return answer; 
        }
        
        answer.push_back({root->val});
        queue<TreeNode*> holder; 
        holder.push(root);
        vector<int> level; 
        
        while (!holder.empty()) {
            TreeNode *temp = holder.front();
            holder.pop();
            if (temp->left != 0) {
                level.push_back(temp->left->val);
                holder.push(temp->left);
            }
            if (temp->right != 0) {
                level.push_back(temp->right->val);
                holder.push(temp->right);
            }
            if (level.size() == holder.size() and level.size() != 0) {
                answer.push_back(level);
                level.clear();
            }
        }
        
        return answer;
    }

Log in to reply
 

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