题目描述
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层序遍历如下:
[
[3],
[20,9],
[15,7]
]
题解
- 使用BFS,每次遍历一层;
- 使用队列维护每一层节点
- 偶数层使用栈结构倒序
代码如下:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<TreeNode*> q;
q.push(root);
int f = 0;
while(q.size())
{
int level_size = q.size();
vector<int> tmp;
stack<int> st;
for(int i=0; i<level_size; i++)
{
TreeNode* n = q.front();
q.pop();
if(!f)
tmp.push_back(n->val);
else
st.push(n->val);
if(n->left)
q.push(n->left);
if(n->right)
q.push(n->right);
}
while(st.size())
{
tmp.push_back(st.top());
st.pop();
}
res.push_back(tmp);
f = !f;
}
return res;
}