题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
解题思路
可参考分行从上到下打印二叉树,可以隔行将顺序的结果逆序就行。
或者一行用栈,另一行用队列来轮着存储。
代码实现
/*
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;
vector <int> arr;
if(!pRoot)return res;
TreeNode *tmp;
queue <TreeNode *> node;
node.push(pRoot);
int row=1,curr=0;
while(!node.empty()){
tmp=node.front(),arr.push_back(tmp->val);
row--,node.pop();
if(tmp->left)node.push(tmp->left),curr++;
if(tmp->right)node.push(tmp->right),curr++;
if(!row){
res.push_back(arr),row=curr,curr=0,arr.clear();
}
}
for(int i=1;i<res.size();i+=2)reverse(res[i].begin(),res[i].end());
return res;
}
};
运行时间:2ms
占用内存:464k