使用双栈,一个栈表示当前层,一个栈表示下一层
换层时交换指向栈的指针
还需要判断当前层时偶数层还是奇数层,偶数层左子节点先入栈,奇数次右子节点先入栈
#include <iostream>
#include <numeric>
#include<algorithm>
#include <stack>
#include <queue>
using namespace std;
struct Tree
{
double value;
Tree* left;
Tree* right;
};
void ZPrint(Tree* root)
{
if (root == NULL)
return;
stack<Tree*> queue_current;
stack<Tree*> queue_next;
auto * p_current = &queue_current;
auto * p_next = &queue_next;
Tree* p = root;
p_next->push(p);
int deep(-1);
while (!(*p_next).empty())
{
std::swap(p_current, p_next);
deep++;
while (!(*p_current).empty())
{
p = p_current->top();
p_current->pop();
cout << p->value << " ";
if ((deep & 1) == 0)//位运算优先级低于==
{
if (p->left != NULL)
p_next->push(p->left);
if (p->right != NULL)
p_next->push(p->right);
}
else
{
if (p->right != NULL)
p_next->push(p->right);
if (p->left != NULL)
p_next->push(p->left);
}
}
cout << endl;
}
}
int main()
{
Tree root;
Tree node1_1;
Tree node1_2;
Tree node2_1;
Tree node2_2;
Tree node2_3;
Tree node3_1;
Tree node3_2;
Tree node3_3;
Tree node3_4;
root.value = 0;
node1_1.value = 1.1;
node1_2.value = 1.2;
node2_1.value = 2.1;
node2_2.value = 2.2;
node2_3.value = 2.3;
node3_1.value = 3.1;
node3_2.value = 3.2;
node3_3.value = 3.3;
node3_4.value = 3.4;
root.left = &node1_1;
root.right = &node1_2;
node1_1.left = &node2_1;
node1_1.right = &node2_2;
node1_2.left = &node2_3;
node1_2.right = NULL;
node2_1.left = &node3_1;
node2_1.right = &node3_2;
node2_2.left = NULL;
node2_2.right = NULL;
node2_3.left = &node3_3;
node2_3.right = &node3_4;
node3_1.left = NULL;
node3_1.right = NULL;
node3_2.left = NULL;
node3_2.right = NULL;
node3_3.left = NULL;
node3_3.right = NULL;
node3_4.left = NULL;
node3_4.right = NULL;
ZPrint(&root);
return 0;
}