标签:层次遍历 相同 dir for div ref push href https
锯齿形层次遍历,思路与二叉树的层次遍历相同,稍微做点改动,区别在于此处使用的是双端队列,分别从前到后和从后到前地遍历二叉树。代码如下
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; }
标签:层次遍历 相同 dir for div ref push href https
原文地址:https://www.cnblogs.com/kuadoh/p/13763175.html