题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/*
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) {
vector<vector<int> >A;
vector<int>B;
if(pRoot==NULL)
return A;
TreeNode*curLast=pRoot,*nextLast=NULL;
queue<TreeNode*>que;
que.push(pRoot);
bool flag=true;
while(!que.empty()){
TreeNode*node=que.front();
que.pop();
if(node->left){
que.push(node->left);
nextLast=node->left;
}
if(node->right){
que.push(node->right);
nextLast=node->right;
}
B.push_back(node->val);
if(node==curLast){
if(flag){
A.push_back(B);
}
else{
reverse(B.begin(), B.end());
A.push_back(B);
}
curLast=nextLast;
B.clear();
flag=!flag;
}
}
return A;
}
};
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) {
vector<vector<int> >A;
vector<int>B;
if(pRoot==NULL)
return A;
TreeNode*curLast=pRoot,*nextLast=NULL;
queue<TreeNode*>que;
que.push(pRoot);
bool flag=true;
while(!que.empty()){
TreeNode*node=que.front();
que.pop();
if(node->left){
que.push(node->left);
nextLast=node->left;
}
if(node->right){
que.push(node->right);
nextLast=node->right;
}
B.push_back(node->val);
if(node==curLast){
if(flag){
A.push_back(B);
}
else{
reverse(B.begin(), B.end());
A.push_back(B);
}
curLast=nextLast;
B.clear();
flag=!flag;
}
}
return A;
}
};