leetcode-----103. 二叉树的锯齿形层次遍历

代码

/**
 * 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>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        if (!root) return ans;
        queue<TreeNode*> q;
        q.push(root);
        int cnt = 0;

        while (q.size()) {
            int len = q.size();
            vector<int> level;
            while (len--) {
                auto t = q.front();
                q.pop();
                level.push_back(t->val);
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
            if (++ cnt % 2 == 0) reverse(level.begin(), level.end());
            ans.push_back(level);
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/clown9804/p/13340250.html