Simple yet still accepted as best in cpp


  • 1
    class Solution {
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<TreeNode*> v0, v1;
            deque<int> d;
            int level = 1;
            vector<vector<int>> vv;
            if(!root) return vv;
            v0.push_back(root);
            while(v0.size())
            {
                for(auto& node: v0)
                {
                    if(node->left) v1.push_back(node->left);
                    if(node->right) v1.push_back(node->right);
                    if(level%2) d.push_back(node->val);
                    else d.push_front(node->val);
                }
                level++;
                v0.swap(v1);
                v1.clear();
                vv.push_back(vector<int>(d.begin(), d.end()));
                d.clear();
            }
            return vv;
        }
    };

  • 0
    C

    Not the best, i checked yours is 5ms using deque whereas mine and many other have a 4ms using queue.


  • 1

    The time cost from OJ fluctuates always, even some variable names can affect it strongly sometimes, the algorithm is the key, man. Don't take it too serious, Dude.


Log in to reply
 

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