Simple C++ Code


  • 0
    G
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> r;
            queue<TreeNode*> my_q;
            if (root) my_q.push(root);
            int direction = 0;  // 0 - go right; 1 - go left
            while (!my_q.empty()) {
                int cur_size = my_q.size();
                r.push_back(vector<int>());
                for (int i = 0; i < cur_size; i++) {
                    TreeNode* front = my_q.front();
                    my_q.pop();
                    r.back().push_back(front->val);
                    if (front->left) my_q.push(front->left);
                    if (front->right) my_q.push(front->right);
                }
                if (direction == 1) reverse(r.back().begin(), r.back().end());
                direction ^= 1;
            }
            return r;
        }
    

Log in to reply
 

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