按照层来,根为第一层,每一层将值加入vector中,如果当前层是2的倍数,就对该vector进行reverse,然后将该vec加入结果数组中,每一层都要讲vec清空
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
void bfs(vector<vector<int>>& res, TreeNode* node){
queue<TreeNode*> q;
q.push(node);
int level = 1;
vector<int> vec;//每一层
while(!q.empty()){
int sz = q.size();
while(sz--!=0){
TreeNode* topNode = q.front();
q.pop();
vec.push_back(topNode->val);
if(topNode->left!=NULL) q.push(topNode->left);
if(topNode->right!=NULL) q.push(topNode->right);
}
if(level%2==0) reverse(vec.begin(),vec.end());
res.push_back(vec);
vec.clear();
level++;
}
}
vector<vector<int> > Print(TreeNode* pRoot) {
//bfs,来一个记录层,首层为第一层,如果为单数,就不反转,如果是双数,就反转再push
vector<vector<int>> res;
if(pRoot == NULL) return res;
bfs(res,pRoot);
return res;
}
};