- 请实现一个函数按照之字形打印二叉树
- 即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推
题目解读
代码
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
int current = 0;
int next = 1;
stack<TreeNode *> levels[2];
vector<vector<int> > pp;
vector<int> pp_core;
if(pRoot == NULL){
return pp;
}
levels[current].push(pRoot);
while(!levels[current].empty() || !levels[next].empty()){
TreeNode *temp = levels[current].top();
levels[current].pop();
pp_core.push_back(temp -> val);
if(current == 0){
if(temp -> left){
levels[next].push(temp -> left);
}
if(temp -> right){
levels[next].push(temp -> right);
}
}
else{
if(temp -> right){
levels[next].push(temp -> right);
}
if(temp -> left){
levels[next].push(temp -> left);
}
}
if(levels[current].empty()){
pp.push_back(pp_core);
pp_core.clear();
current = 1 - current;
next = 1 - next;
}
}
return pp;
}
};
总结展望