6ms AC solution in C++


  • 0
    L

    This is my first post. Simple straightforward BFS method with reverse operation.

    Thanks!

    class Solution {
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            int flag = 0;
            vector<TreeNode*> level;
            vector<vector<int>> res;
            if(!root) return res;
            level.push_back(root);
            while(1){
                vector<TreeNode*> temp;
                vector<int> t;
                for(auto node : level){
                    t.push_back(node->val);
                    if(node->left) temp.push_back(node->left);
                    if(node->right) temp.push_back(node->right);
                }
                level.swap(temp);
                if(flag%2 == 1) reverse(t.begin(), t.end());
                flag++;
                res.push_back(t);
                if(level.size() == 0) break;
            }
            return res;
        }
    };
    

Log in to reply
 

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