题目描述:
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]解题思路:
二叉树的层次遍历,使用两个队列,一个队列保存层次遍历的结点,另一个队列保存层次遍历结点对应的深度,把相同深度的结点的值放到同一个数组中,
最后再对奇数索引的数组中的元素值进行翻转即可。
AC代码如下:
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root){
vector<vector<int>> ans;
if (root == NULL) return ans;
queue<TreeNode*> nodes;
queue<int> levels;
nodes.push(root);
levels.push(1);
vector<int> values;
int cur_level = 1;
while (!nodes.empty()){
TreeNode* node = nodes.front();
nodes.pop();
int level = levels.front();
levels.pop();
if (level == cur_level){
values.push_back(node->val);
}
else{
ans.push_back(values);
values.clear();
values.push_back(node->val);
cur_level = level;
}
if (node->left != NULL){
nodes.push(node->left);
levels.push(level + 1);
}
if (node->right != NULL){
nodes.push(node->right);
levels.push(level + 1);
}
}
if (values.size()>0) ans.push_back(values);
for (int i = 0; i < ans.size(); ++i){
if (i % 2 == 1){
ans[i] = vector<int>(ans[i].rbegin(), ans[i].rend());
}
}
return ans;
}
};