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] ]
冥思苦想是如何打印?
结果发现是输出二维vector
事情变得容易很多
先写一个广序遍历二叉树
然后往里面填充
结果语法报错??
发现写的有点蠢
每行结束多加一个NULL就可以解决
最后的最后按着一维去反转
/**
* 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> > ans;
vector<int>tmp;
queue<TreeNode*>q;
q.push(root);
q.push(NULL);
while(!q.empty()) {
TreeNode* thi = q.front();
q.pop();
if(thi == NULL) {
ans.push_back(tmp);
tmp.resize(0);
if(!q.empty()) {
q.push(NULL);
}
} else {
tmp.push_back(thi->val);
if(thi->left!=NULL) {
q.push(thi->left);
}
if(thi->right!=NULL) {
q.push(thi->right);
}
}
}
for(int i = 1;i < ans.size();i+=2) {
reverse(ans[i].begin(),ans[i].end());
}
return ans;
}
};