题目描述
给定一个二叉树,返回该二叉树的之字形层序遍历,(从左向右,下一层从右向左,一直这样交替)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
3↵ / ↵ 9 20↵ / ↵ 15 7
该二叉树之字形层序遍历的结果是
[↵ [3],↵ [20,9],↵ [15,7]↵]
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},
3↵ / ↵ 9 20↵ / ↵ 15 7↵
return its zigzag level order traversal as:
[↵ [3],↵ [20,9],↵ [15,7]↵]↵
思路:
- 二叉树的层序遍历考虑用队列来求解;
- 题目要求Z字形遍历,则不能按照正常顺序入队,由于入队顺序与之前相反,所以考虑用栈来辅助入队;
- 设置枚举量表示遍历的方向(从左向右,从右向左);
代码:
/**
* Definition for binary tree
* 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) {
vector<vector<int> > ans;
if (root == nullptr)
return ans;
stack<TreeNode *> s;
queue<TreeNode *> q;
enum Turn{left, right};
Turn turn = left;
q.push(root);
while (!q.empty())
{
vector<int> tmp;
if (turn == left)
{
while (!q.empty())
{
TreeNode *node = q.front();
tmp.push_back(node->val);
if (node->left) s.push(node->left);
if (node->right) s.push(node->right);
q.pop();
}
turn = right;
}
else
{
while (!q.empty())
{
TreeNode *node = q.front();
tmp.push_back(node->val);
if (node->right) s.push(node->right);
if (node->left) s.push(node->left);
q.pop();
}
turn = left;
}
ans.push_back(tmp);
while (!s.empty())
{
q.push(s.top());
s.pop();
}
}
return ans;
}
};