按之字形顺序打印二叉树
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
没有堆栈来回倒的过程
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> ret;
if (nullptr == pRoot) {
return ret;
}
stack<TreeNode *> levels[2];
vector<int> vt;
int current = 1;
int next = 0;
levels[current].push(pRoot);
while ((!levels[0].empty()) || (!levels[1].empty())) {
TreeNode *temp = levels[current].top();
levels[current].pop();
vt.push_back(temp->val);
if (1 == current) {
if (nullptr != temp->left) {
levels[next].push(temp->left);
}
if (nullptr != temp->right) {
levels[next].push(temp->right);
}
}
else {
if (nullptr != temp->right) {
levels[next].push(temp->right);
}
if (nullptr != temp->left) {
levels[next].push(temp->left);
}
}
if (levels[current].empty()) {
ret.push_back(vt);
vt.resize(0);
current = 1 - current;
next = 1 - next;
}
}
return ret;
}
};
与从上到下打印树只相差一个翻转函数和奇偶判断
与上面方法相比, 多一步倒换堆栈的过程, 若不用翻转数组, 则需根据奇偶判断是倒堆栈还是复制堆栈
class Solution {
public:
// 偶数层翻转容器
vector<int> reserveOrder(vector<int> vt) {
vector<int> ret;
for (int i = vt.size() - 1; i >= 0; i--) {
ret.push_back(vt[i]);
}
return ret;
}
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> ret;
if (nullptr == pRoot) {
return ret;
}
stack<TreeNode *> global;
global.push(pRoot);
bool isEnd = false;
int i = 0;
while (false == isEnd) {
i++;
isEnd = true;
stack<TreeNode *> local;
vector<int> vt;
while (!global.empty()) {
TreeNode *temp = global.top();
global.pop();
if (nullptr != temp) {
vt.push_back(temp->val);
local.push(temp->left);
local.push(temp->right);
if ((nullptr != temp->left) || (nullptr != temp->right)) {
isEnd = false;
}
}
else {
local.push(nullptr);
local.push(nullptr);
}
}
while(local.size()) {
global.push(local.top());
local.pop();
}
if (i % 2) { // 奇数层, 从左到右
ret.push_back(vt);
}
else { // 偶数层, 从右到做
ret.push_back(reserveOrder(vt)); // 翻转容器
}
}
return ret;
}
};
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};