题目讲解
103. 二叉树的锯齿形层序遍历
算法讲解
这道题其实是和N叉树层序遍历是一样的,只不过是要求每一次的遍历的方向不一样;注意:这一次的使用的队列不能够是queue了,因为需要从后往前遍历容器,所以就可以使用vector作为队列
/*** 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>> ret;int flag = 1; //第一次从左向右if(!root)return ret;vector<TreeNode*>q;q.push_back(root);while(!q.empty()){int levesize = q.size();vector<int>temp;//遍历层序 分左右if(flag){for(int i = 0; i < levesize; i++){if(q[i])temp.push_back(q[i]->val);}flag = 0;} else {for(int i = levesize-1; i >=0; i--){if(q[i])temp.push_back(q[i]->val);}flag = 1;}//往队列里面赛数据 塞下一层的节点for(int i = 0; i < levesize; i++){TreeNode* cur = q.front();q.erase(q.begin()); //删除队列首部元素if(cur->left)q.push_back(cur->left);if(cur->right)q.push_back(cur->right);}ret.push_back(temp);}return ret;}
};