剑指offer—按之字形顺序打印二叉树

时间:2023-01-28 14:30:53

华电北风吹
天津大学认知计算与应用重点实验室
日期:2015/10/8

题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

解析:与前面遇到的哪个按行打印二叉树类似,区别是这里设置的flag不用移动,从左往右访问是先左子树后右子树,从右往左访问的时候先右子树后左子树即可。

/*
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;
TreeNode * flag = new TreeNode(NULL);
deque<TreeNode *> q;
q.push_back(pRoot);
q.push_back(flag);
vector<int> temp;
bool lefttoright = true;
while (q.size()>1)
{
if (lefttoright)
{
TreeNode * top = q.front();
if (top == flag)
{
result.push_back(temp);
temp.clear();
lefttoright = false;
continue;
}
q.pop_front();
temp.push_back(top->val);
if (top->left != NULL)
q.push_back(top->left);
if (top->right != NULL)
q.push_back(top->right);
}
else
{
TreeNode * end = q.back();
if (end == flag)
{
result.push_back(temp);
temp.clear();
lefttoright = true;
continue;
}
q.pop_back();
temp.push_back(end->val);
if (end->right != NULL)
q.push_front(end->right);
if (end->left != NULL)
q.push_front(end->left);
}
}
result.push_back(temp);
return result;
}
};