leetcode103. 二叉树的锯齿形层序遍历

分析

利用双端队列来控制入队的方向,从而达到交替访问的效果。

/**
 * 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>> ans;
    queue<TreeNode*>q;
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        if(!root)return ans;
        q.push(root);
        bool direction=true;
        while(q.size()){
            deque<int>level;
            int size=q.size();
            for(int i=0;i<size;i++){
                auto t=q.front();
                q.pop();
                if(direction){//从左往右
                    level.push_back(t->val);
                }else{//从右往左
                    level.push_front(t->val);
                }
                if(t->left)q.push(t->left);
                if(t->right)q.push(t->right);
            }
            direction=!direction;
            ans.push_back(vector<int>{level.begin(),level.end()});
        }
        return ans;
    }
};