思路:
这道题我们可以用队列来做的,你会发现只要我们每两层之间翻转一层即可,基本的框架还是bfs,具体可以看代码。
代码:
/**
* 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>> ans;
if (!root) {
return ans;
}
queue<TreeNode*> nodeQueue;
nodeQueue.push(root);
bool isOrderLeft = true;
while (!nodeQueue.empty()) {
vector<int> levelList;
int size = nodeQueue.size();
for (int i = 0; i < size; ++i) {
auto node = nodeQueue.front();
nodeQueue.pop();
levelList.push_back(node->val);
if (node->left) {
nodeQueue.push(node->left);
}
if (node->right) {
nodeQueue.push(node->right);
}
}
if(isOrderLeft)
ans.emplace_back(vector<int>{levelList.begin(), levelList.end()});
else
ans.emplace_back(vector<int>{levelList.rbegin(), levelList.rend()});
isOrderLeft = !isOrderLeft;
}
return ans;
}
};
如果苛刻点,是按照点来层序遍历,要像个之字形遍历点怎么办?
还是会用到deque或者list容器;
用一个变量 odd ;
//一开始先把头结点值放到vector<vector<>>中
if(odd)
{
//右左遍历
//这时就要输出值,放到vector<vector<>> 中,
}
else
{
//左右遍历
//这时就要输出值,放到vector<vector<>> 中
}