My 4ms C++ solution using one queue, beats 78.81%


  • 3
    M
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            
            vector<vector<int>> tree;
            vector<int> level;
            
            if(root == NULL)
                return tree;
            
            queue<TreeNode *> q;
            int currLevel = 1;
            int nextLevel = 0;
            
            q.push(root);
            while(!q.empty())
            {
                TreeNode* node = q.front();
                q.pop();
                currLevel--;
                level.push_back(node->val);
                if(node->left)
                {
                    q.push(node->left);
                    nextLevel++;
                }
                if(node->right)
                {
                    q.push(node->right);
                    nextLevel++;
                }
                if(currLevel == 0)
                {
                    tree.push_back(level);
                    level.clear();
                    currLevel = nextLevel;
                    nextLevel = 0;
                }
            }
            
            return tree;
        }
    };

  • 0
    G

    That's a neat concept!
    Although I feel like my solution is clearer, takes the same amount of time, and actually more memory efficient (using emplace instead of push_back).

    {
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ret;
        if (root == nullptr) return ret;
        deque<TreeNode*> s;
        s.push_back(root);
        s.push_back(nullptr);
        ret.emplace_back();
        while (!s.empty()) {
            auto front = s.front();
            s.pop_front();
            if (front == nullptr) {
                if (!s.empty()) {
                    ret.emplace_back();
                    s.push_back(nullptr);
                }
                continue;
            }
            
            ret.back().push_back(front->val);
            if (front->left) s.push_back(front->left);
            if (front->right) s.push_back(front->right);
        }
    }
    }

  • 0
    P

    Thank u, smart ideal!


Log in to reply
 

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