二叉树的建立及中后序遍历

Problem Description

按照给定的扩展二叉树前序遍历序列建立相应的非空二叉树,要求采用二叉链表进行存储表示,并对其进行中序和后序遍历,输出中后序遍历序列后请销毁二叉链表以释放内存。
Input

第一行为一个整数n,表示以下有n组数据,每组数据占一行,为扩展二叉树的前序遍历序列。
Output

输出该二叉树的中序和后序遍历序列,每个序列占一行,每两组输出之间有一换行。
Sample Input

3
AB#D##C##
AB##C#D##
ABD##E##C#F##
Sample Output

BDAC
DBCA

BACD
BDCA

DBEACF
DEBFCA

#include<iostream>
using namespace  std;
struct BiNode
{
	char data;
	BiNode *lchild,
		*rchild;
};
BiNode *creat()
{
	BiNode *bt = NULL;
	char ch;
	cin >> ch;
	if (ch != '#')
	{
		bt = new BiNode;
		bt->data = ch;
		bt->lchild = creat();
		bt->rchild = creat();
	}
	return bt;
}
void InOrder(BiNode *bt)
{
	if (bt)
	{
		InOrder(bt->lchild);
		cout << bt->data;
		InOrder(bt->rchild);
	}
}
void PostOrder(BiNode *bt)
{
	if (bt)
	{
		PostOrder(bt->lchild);
		PostOrder(bt->rchild);
		cout << bt->data;
	}
}
void Release(BiNode *bt)
{
	if (bt)
	{
		Release(bt->lchild);
		Release(bt->rchild);
		delete bt;
	}
}
int main()
{
	int n;
	BiNode *root;
	while (cin >> n)
	{
		while (n--)
		{
			root = creat();
			InOrder(root);
			cout << endl;
			PostOrder(root);
			cout << endl;
			if (n != 0)
				cout << endl;
			Release(root);
		}
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wq6ylc88/article/details/84969983