Binary Tree Zigzag Level Order Traversal My Submissions Question
Total Accepted: 47731 Total Submissions: 176275 Difficulty: Medium
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]
]
confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.
Subscribe to see which companies asked this question
依旧是对树进行层序遍历,之后对序号为奇数的向量进行一次翻转。
不出意料的一次AC,自从看完《剑指offer》之后,觉得学会了边写代码边检查,各种边界条件测试在脑海里一遍遍过。
/**
* 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<TreeNode*> q;
q.push(root);
vector<int> vi;
while(!q.empty()){
int size = q.size();
for(int i = size;i > 0;--i){
TreeNode* t = q.front();
q.pop();
vi.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
res.push_back(vi);
vi.clear();
}
for(int i = 0;i < res.size();++i){
if(i % 2){
reverse(res[i].begin(),res[i].end());
}
}
return res;
}
};