题解 |按Z字形打印二叉树
按之字形顺序打印二叉树
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) {
stack<TreeNode*> s1,s2;
vector<vector<int>> vec;
vector<int> v;
int count=0;
if(pRoot==NULL){
return vec;
}
s1.push(pRoot);
while(!s1.empty()||!s2.empty()){
vector<int> arr;
while(!s1.empty()){
TreeNode* p=s1.top();
s1.pop();
arr.push_back(p->val);
if(p->left){
s2.push(p->left);
}
if(p->right){
s2.push(p->right);
}
}
if(arr.size()){
vec.push_back(arr);
}
arr.clear();
while(!s2.empty()){
TreeNode *p=s2.top();
s2.pop();
arr.push_back(p->val);
if(p->right) s1.push(p->right);
if(p->left) s1.push(p->left);
}
if(arr.size()){
vec.push_back(arr);
}
arr.clear();
}
return vec;
}
};