题目描述:
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
解题思路:
层次遍历,改变是先计算队列的大小,循环存放这一层的节点于vec中,然后将下一层中的节点入列,设置是否反向位,true反向,并存入result中。
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> > result;
if(pRoot==NULL)
return result;
queue<TreeNode*> qt;
qt.push(pRoot);
bool model=false;
while(!qt.empty())
{
vector<int> vec;
int st=qt.size();
for(int i=0;i<st;i++)
{
TreeNode* x=qt.front();
qt.pop();
vec.push_back(x->val);
if(x->left!=NULL)
qt.push(x->left);
if(x->right!=NULL)
qt.push(x->right);
}
if(model)
std::reverse(vec.begin(),vec.end());
result.push_back(vec);
model=!model;
}
return result;
}
};