首页 > 其他 > 详细

leetcode-华为专题-103. 二叉树的锯齿形层序遍历

时间:2021-08-19 15:00:29      阅读:27      评论:0      收藏:0      [点我收藏+]

 

技术分享图片

 

/**
 * 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>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(root==NULL)
            return res;
        queue<TreeNode*> q;
        q.push(root);
        vector<int> temp;
        while(!q.empty()){
            if(temp.size()>0)
                res.push_back(temp);
            int len = q.size();
            temp.clear();
            while(len--){
                TreeNode* tmp = q.front();
                q.pop();
                temp.push_back(tmp->val);
                if(tmp->left)
                    q.push(tmp->left);
                if(tmp->right)
                    q.push(tmp->right);
            }
        }
        res.push_back(temp);
        for(int i = 0; i < res.size(); i++){
            if(i%2==1)  // 奇数行翻转
                reverse(res[i].begin(), res[i].end());
        }
        return res;

    }
};

 

leetcode-华为专题-103. 二叉树的锯齿形层序遍历

原文:https://www.cnblogs.com/ymec/p/15160474.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!