[leetcode] Binary Tree Zigzag Level Order Traversal

Binary Tree Zigzag Level Order Traversal


class Solution {
private:
    vector<vector<int>> res;
public:
    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
        if (root==NULL) {
            return res;
        }
        
        queue<TreeNode*> curQ,nextQ;
        curQ.push(root);
        
        int layer=0;
        
        while (!curQ.empty()) {
            
            layer++;
            vector<int> layerRes;
            
            while (!curQ.empty()) {
                TreeNode *tmp=curQ.front();
                layerRes.push_back(tmp->val);
                curQ.pop();
                
                if (tmp->left!=NULL) {
                    nextQ.push(tmp->left);
                }
                if (tmp->right!=NULL) {
                    nextQ.push(tmp->right);
                }
            }
            curQ=nextQ;//指向下一层
            if (layer%2==0) {//偶数层反序
                reverse(layerRes.begin(), layerRes.end());
            }
            res.push_back(layerRes);
            while (!nextQ.empty()) {//清空下一层
                nextQ.pop();
            }
        }
        return res;
    }
};


你可能感兴趣的:([leetcode] Binary Tree Zigzag Level Order Traversal)