二叉树的建立及前序遍历

Problem Description

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

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

在一行里输出该二叉树的前序遍历序列。
Sample Input

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

ABDC
ABCD
ABDECF

#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 PreOrder(BiNode *bt)
{
	if (bt)
	{
		cout << bt->data;
		PreOrder(bt->lchild);
		PreOrder(bt->rchild);
	}
}
void Release(BiNode *bt)
{
	if (bt)
	{
		Release(bt->lchild)
			; Release(bt->rchild)
			; delete bt;
	}
}
int main()
{
	int n;
	BiNode *root;
	cin >> n;
	while (n--)
	{
		root = creat();
		PreOrder(root);
		cout << endl;
		Release(root);
	}
	system("pause");
	return 0;
}

猜你喜欢

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