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;
    }
};
posted @ 2020-07-19 16:37  景云ⁿ  阅读(136)  评论(0编辑  收藏  举报