欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-21 08:16:42
...
/**
 * 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>> result;
        if(!root) return result;
        bool odd = true;
        queue<TreeNode *> q,tmpQueue;
        vector<int> subResult;
        TreeNode *tmpNode;
        q.push(root);
        while(!q.empty()) {
            tmpNode = q.front();
            q.pop();
            subResult.push_back(tmpNode->val);
            if(tmpNode->left) tmpQueue.push(tmpNode->left);
            if(tmpNode->right) tmpQueue.push(tmpNode->right);
            if(q.empty()) {
                if(!odd) reverse(subResult.begin(),subResult.end());
                result.push_back(subResult);
                odd = !odd;

                q.swap(tmpQueue);
                subResult.clear();
            }
        }
        return result;
    }
};
相关标签: leetcode刷题