题解 | #按之字形顺序打印二叉树#C++版
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
C++版,两个栈解决方案
/*
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> > res;
if(pRoot == nullptr) return res;
vector<int> lvec;
stack<TreeNode*> stk[2];
stk[0].push(pRoot);
TreeNode* p = nullptr;
for(int i = 0; !stk[i].empty(); i = (i+1) % 2) {
lvec.clear();
while (!stk[i].empty()) {
p = stk[i].top();
stk[i].pop();
lvec.push_back(p->val);
if(i == 0){
if(p->left) stk[1].push(p->left);
if(p->right) stk[1].push(p->right);
}else{
if(p->right) stk[0].push(p->right);
if(p->left) stk[0].push(p->left);
}
}
res.push_back(lvec);
}
return res;
}
};