zoukankan      html  css  js  c++  java
  • LeetCode103. 二叉树的锯齿形层次遍历

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

    锯齿形层次遍历,思路与二叉树的层次遍历相同,稍微做点改动,区别在于此处使用的是双端队列,分别从前到后和从后到前地遍历二叉树。代码如下

    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            deque<TreeNode*>q;
            vector<vector<int>>res;
            if (root==NULL)return res;
            else{
                q.push_back(root);
                bool dir=true;//标志位,指示从前往后还是从后往前遍历层级
                while(!q.empty())
                {
                    int n=q.size();
                    vector<int>r;
                    for(int i=0;i<n;i++)
                    {
                        if(dir)//注意遍历的方式和左右结点的插入位置
                        {
                            TreeNode *cur=q.front();
                            q.pop_front();
                            r.push_back(cur->val);
                            if(cur->left!=NULL)
                                q.push_back(cur->left);
                            if(cur->right!=NULL)
                                q.push_back(cur->right);
                        }
                        else{
                            TreeNode *cur=q.back();
                            q.pop_back();
                            r.push_back(cur->val);
                            
                            if(cur->right!=NULL)
                                q.push_front(cur->right);
                            if(cur->left!=NULL)
                                q.push_front(cur->left);
                        }
                    }
                    res.push_back(r);
                    dir=!dir;//遍历一层后反过来遍历
                }
            }
            return res;
        }
  • 相关阅读:
    暂时转换
    内置函数⼆
    day13内置函数⼀
    day12⽣成器和⽣成器表达式
    20181031作业
    20181030函数2
    20181029函数1
    20181026
    20181025
    20181024
  • 原文地址:https://www.cnblogs.com/kuadoh/p/13763175.html
Copyright © 2011-2022 走看看