题目链接
tag:
- Medium;
- queue;
question:
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).
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]
]
思路:
本题和102. 二叉树层序遍历类似。通过一个队列来控制,仍然是当做一个普通的 BFS
来实现。唯一不同的是,判断是否需要将当前的数组反转。在程序中定义一个标签(flag)来实现。flag代表树的深度,根节点为零。树的深度为奇数的时候,不需要反转,树的深度为偶数的时候,需要反转。代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
if (!root) return {};
vector<vector<int>> res;
queue<TreeNode*> q;
q.push(root);
int flag = 0; // tree depth
while (!q.empty()) {
vector<int> level;
for (int i=q.size(); i>0; --i) {
TreeNode *tmp = q.front();
q.pop();
level.push_back(tmp->val);
if (tmp->left) q.push(tmp->left);
if (tmp->right) q.push(tmp->right);
}
++flag;
if (flag & 1)
res.push_back(level);
else {
reverse(level.begin(), level.end());
res.push_back(level);
}
}
return res;
}
};
类似题目: