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;
    }

 

posted @ 2020-10-03 00:10  kuadoh96  阅读(140)  评论(0编辑  收藏  举报