题目
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,#,#,15,7},
return its zigzag level order traversal as:
分析
之字型层序遍历二叉树。
此题目与上一题LeetCode 102 Binary Tree Level Order Traversal 本质相同,只需要添加一个标志变量控制当前层是之字正序还是之字逆序。
详见代码:
AC代码
/**
* 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> >();
//定义f作为是否需要逆序的标记,true代表该层为之字正序
bool f = true;
vector<vector<int> > ret;
//定义两个队列,一个存储所有的父节点,另一个存储他们的子节点也就是子层
queue<TreeNode *> parents;
parents.push(root);
while (!parents.empty())
{
//存储当前层的遍历结果
vector<int> tmp;
//定义队列存储他们的子节点也就是子层
queue<TreeNode *> childs;
while (!parents.empty())
{
TreeNode *node = parents.front();
tmp.push_back(node->val);
//弹出当前父节点
parents.pop();
if (node->left)
childs.push(node->left);
if (node->right)
childs.push(node->right);
}
//当前层应之字正序
if (f)
{
//存储当前层的遍历结果
ret.push_back(tmp);
//下一层为之字逆序
f = false;
}
//当前层为之字逆序
else{
//反转当前层节点遍历结果
reverse(tmp.begin(), tmp.end());
ret.push_back(tmp);
//下一层为之字正序
f = true;
}
//遍历下一层
parents = childs;
}
return ret;
}
};