PAT A1127 ZigZagging on a Tree

/*---------------------------------------------

	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)?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值