/*---------------------------------------------
PAT A1127 ZigZagging on a Tree
题意:层序基础上Z字形遍历二叉树
题解:用双端序列,
深度为奇时:栈输出;
深度为偶时:队列输出。
---------------------------------------------*/
#include<iostream>
#include<fstream>
#include<deque>
using namespace std;
struct Node
{
int Data;
Node* Lchild;
Node* Rchild;
};
//中序,后序序列
int Inorder[35], Postorder[35];
int Node_Number;//节点数
//减少使用全局变量的意义在小程序中体现不出来,不需要太在意
//纠正PAT1126中的话
int Count = 1;
deque <int> Dq[35];
//根据中序,后序递归建树
Node* CreateTree(int InL, int InR, int PostL, int PostR);
//先序遍历查看建树是否正确
void Post_Traveral(Node* Root);
//根据深度对节点入队
void LevelOrder_Traveral(Node* Root, int Deepth);
int main()
{
#ifdef _DEBUG
ifstream cin("Input.txt");
#endif
cin >> Node_Number;
//输入中序序列
for (int i = 1; i <= Node_Number; ++i)
cin >> Inorder[i];
//输入后序序列
for (int i = 1; i <= Node_Number; ++i)
cin >> Postorder[i];
//递归建树
Node* Root = CreateTree(1, Node_Number, 1, Node_Number);
LevelOrder_Traveral(Root, 0);
cout << Dq[1].front();
for (int Deepth = 2; Deepth < 35; ++Deepth)
{
if (Deepth % 2 == 1) //奇数时,栈输出
while (!Dq[Deepth].empty())
{
cout << ' ' << Dq[Deepth].back();
Dq[Deepth].pop_back();
}
else //偶数时,队列输出
while (!Dq[Deepth].empty())
{
cout << ' ' << Dq[Deepth].front();
Dq[Deepth].pop_front();
}
}
#ifdef _DEBUG
cin.close();
#endif
return 0;
}
//递归建树
Node* CreateTree(int InL, int InR, int PostL, int PostR)
{
if (InL > InR)
return NULL;
Node *Root = new Node;
Root->Data = Postorder[PostR];
int i;
for (i = InL; i <= InR; ++i)
if (Inorder[i] == Postorder[PostR])
break;
int LeftSubTree = i - InL;
Root->Lchild = CreateTree(InL, i - 1, PostL, PostL + LeftSubTree - 1);
Root->Rchild = CreateTree(i + 1, InR, PostL + LeftSubTree, PostR - 1);
return Root;
}
//先序遍历查看建树是否正确
void Post_Traveral(Node* Root)
{
if (Root == NULL)
return;
cout << Root->Data;
if (Count++ != Node_Number)
cout << ' ';
Post_Traveral(Root->Lchild);
Post_Traveral(Root->Rchild);
}
//根据深度对节点入队
void LevelOrder_Traveral(Node* Root, int Deepth)
{
if (Root == NULL)
return;
++Deepth;
Dq[Deepth].push_back(Root->Data);
LevelOrder_Traveral(Root->Lchild, Deepth);
LevelOrder_Traveral(Root->Rchild, Deepth);
}
为什么没有预览(Preview)?
PAT A1127 ZigZagging on a Tree
最新推荐文章于 2022-11-20 17:40:31 发布