Posted on

Description

Submission

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        if(!root) return {};
        bool isReversed = false;
        vector<vector<int>> rets;

        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()) {
            int n = q.size();

            vector<int> row;
            while(n--) {
                TreeNode* node = q.front();
                q.pop();

                row.push_back(node->val);
                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
            }
            if(isReversed) {
                reverse(row.begin(), row.end());
            }
            isReversed = !isReversed;

            rets.push_back(row);
        }

        return rets;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *