您的位置:首页 > 职场人生

面试题68:按之字形顺序打印二叉树

2016-03-30 19:59 363 查看
题目:

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

思路:

可以用两个队列来实现,当一个队列为空时,换行,所以不需要额外存储层数。

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

struct Node{
int val;
Node *left;
Node *right;
Node(int _val) :val(_val), left(NULL), right(NULL){}
};

void PrintByLevel(Node *root)
{
if (!root) return;
stack<Node*> S[2];
int flag = 0;
S[flag].push(root);
int outLevel = 1;
while (!S[flag].empty())
{
Node* temp = S[flag].top();
cout << temp->val << " ";
S[flag].pop();
if (flag == 0)
{
if (temp->left) S[1 - flag].push(temp->left);
if (temp->right) S[1 - flag].push(temp->right);
}
else
{
if (temp->right) S[1 - flag].push(temp->right);
if (temp->left) S[1 - flag].push(temp->left);
}
if (S[flag].empty())
{
flag = 1 - flag;
cout << endl;
}
}
cout << endl;
}

int main()
{
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
Node *n6 = new Node(6);
Node *n7 = new Node(7);
Node *n8 = new Node(8);
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
n3->left = n6;
n3->right = n7;
n7->right = n8;
PrintByLevel(n1);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: