Share my c++ implementation 4ms


  • 0
    L
    class Solution {
    public:
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            vector<vector<int>> levels;
            if (root==NULL) return levels;
            
            queue<TreeNode *> q;
            q.push(root);q.push(NULL);
            
            vector<int> level;
            while (!q.empty()) {
                TreeNode *node = q.front();
                q.pop();
                
                if (node==NULL) // using NULL as delimiter for each level.
                {
                    // NULL means done with one level
                    levels.push_back(level);
                    level.clear();
                    if (!q.empty()) q.push(NULL);
                } else {
                    level.push_back(node->val);
                    if (node->left) q.push(node->left);
                    if (node->right) q.push(node->right);
                }
            }
            reverse(levels.begin(),levels.end());
            return levels;
        }
    };

Log in to reply
 

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