题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
/*
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>> ans;
vector<int> flag;
if(!pRoot)
return ans;
queue<TreeNode*> temp;
queue<TreeNode*> tempPlus;
temp.push(pRoot);
int num=1;
while(!temp.empty())
{
TreeNode* cur = temp.front();
flag.push_back(cur->val);
temp.pop();
if(cur->left)
tempPlus.push(cur->left);
if(cur->right)
tempPlus.push(cur->right);
if(temp.empty())
{
temp = tempPlus;
queue<TreeNode*> odd;
tempPlus = odd;
if(num%2==0)
reverse(flag.begin(), flag.end());
ans.push_back(flag);
num++;
flag.clear();
}
}
return ans;
}
};