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

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


题目链接:103. 二叉树的锯齿形层序遍历

代码如下:

/**
 * 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;
        int count=0;

        if(root==nullptr)
            return res;
        queue<TreeNode*> que;
        que.push(root);

        //层次遍历
        while(!que.empty())
        {
   
            int len=que.size();
            vector<int> temp;

            for(int i=0;i<len;i++)
            {
   
                root=que.front();
                que.pop();

                temp.push_back(root->val);
                if(root->left)
                    que.push(root->left);
                if(root->right) 
                    que.push(root->right);
            }

            if(count%2==1)
                reverse(temp.begin(),temp.end());
            count++;
            res.push_back(temp);
        }

        return res;
    }
};

相关推荐

  1. 103. 锯齿

    2024-01-06 12:40:04       44 阅读
  2. 力扣103. 锯齿

    2024-01-06 12:40:04       34 阅读
  3. LeetCode [103] 锯齿

    2024-01-06 12:40:04       35 阅读
  4. 【力扣刷题练习】103. 锯齿

    2024-01-06 12:40:04       42 阅读
  5. 【C++】每日一题 103 锯齿

    2024-01-06 12:40:04       11 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-06 12:40:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-06 12:40:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-06 12:40:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-06 12:40:04       18 阅读

热门阅读

  1. 详细介绍Spring Boot 和 Spring 有什么区别

    2024-01-06 12:40:04       28 阅读
  2. Ceph分布式存储

    2024-01-06 12:40:04       25 阅读
  3. 基于长短期神经网络lstm的求解方程

    2024-01-06 12:40:04       35 阅读