/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
//用于层序遍历
queue<TreeNode*> q;
//判断是否需要逆序输出
bool stack_flag = false;
vector<vector<int> > ans;
if(pRoot==nullptr) return ans;
q.push(pRoot);
while(!q.empty()){
//n为当前层的元素个数,下面的for循环用于区别不同层的的元素
int n = q.size();
vector<int> subvec;
subvec.reserve(n);
for(int i=0; i< n; i++){
TreeNode* temp = q.front();
subvec.push_back(temp->val);
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
q.pop();
}
//如果是偶数层,则逆序储存,达到之字形输出的目的
if(stack_flag) reverse(subvec.begin(), subvec.end());
ans.push_back(subvec);
stack_flag = !stack_flag;
}
return ans;
}
};