BFS
算法概论第五周
103. Binary Tree Zigzag Level Order Traversal
题目描述
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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
思路分析
- BFS的经典应用,层次遍历
- 最后结果奇数行reverse即可
pair
包含utility
,reverse
包含algorithm
代码实现
/**
* 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) {
vector<vector<int> > res;
if(!root)
return res;
queue<pair<TreeNode*, int> > que;
que.push(make_pair(root, 0));
while(!que.empty()){
TreeNode* now = que.front().first;
int level = que.front().second;
que.pop();
if(res.size() <= level){
vector<int> tmp;
tmp.push_back(now->val);
res.push_back(tmp);
}
else{
res[level].push_back(now->val);
}
if(now->left){
que.push(make_pair(now->left, level + 1));
}
if(now->right){
que.push(make_pair(now->right, level + 1));
}
}
for(int i = 0; i < res.size(); i++){
if(i & 1 == 1){
reverse((*(res.begin() + i)).begin(), (*(res.begin() + i)).end());
}
}
return res;
}
};