二叉树根据前序遍历输出中序后序层次遍历

题目

编写完整程序,用先序遍历法建立二叉树的二叉链表存储结构。输出该二叉树的先、中、后序遍历结点访问次序以及层次遍历结点访问次序。

源代码

#include
#include
#include
using namespace std;
//made by  LinHeng
int countnode = 0;
typedef struct Tree
{
	char e;
	Tree* lchild;
	Tree* rchild;
	Tree* parent;
}T;//二叉树三叉链表

struct Queue
{
	T* Container;
	int rear;
	int front;
	int size;
};//队列,用于层次遍历
int enQueue(Queue &q,T e)
{
	if ((q.rear + 1) % q.size == q.front % q.size)
		return 0;//队列满
	else
	{
		q.rear = (q.rear + 1) % q.size;
		q.Container[q.rear] = e;
		return 1;
	}
}//循环队列入队操作

int dlQueue(Queue& q, T &e)
{
	if (q.rear == q.front)
		return 0;//队列空
	else
	{
		q.front = (q.front + 1) % q.size;
		e = q.Container[q.front];
		return 1;
	}
}//循环队列出队操作

int Empty(Queue& q)
{
	if (q.rear == q.front)
		return 1;//队列空
	else
		return 0;
}//判断队列是否为空
void InitializeQueue(Queue& q,int size)
{
	q.size = size;
	q.Container = new T[size];
	q.rear = -1;
	q.front = -1;
}//根据指定大小初始化队列

T*  CreatTree(T* bt,char *temp)//先序建立二叉树
{
	static int i = 0;
	char c;

	if ( (c=temp[i++])== '#')//括号很重要,因为==的优先级大于赋值运算符
		return 0;
	else
	{
		bt = new T;
		countnode++;
		bt->e = c;
		bt->lchild=CreatTree(bt->lchild,temp);
		bt->rchild=CreatTree(bt->rchild,temp);
		return bt;
	}
}

void Preorder(T* bt)
{
	if (!bt)return;
	else 
	{
		cout << bt->e << " ";
		Preorder(bt->lchild);
		Preorder(bt->rchild);
	}
}//前序遍历

void Midorder(T* bt)
{
	if (!bt)return;
	Midorder(bt->lchild);
	cout << bt->e << " ";
	Midorder(bt->rchild);
}//中序遍历

void Lasorder(T* bt)
{
	if (!bt)return;
	Lasorder(bt->lchild);
	Lasorder(bt->rchild);
	cout << bt->e << " ";
}//后序遍历

void layer(T* bt,Queue queue)
{
	T e;
	enQueue(queue, *bt);
	while (!Empty(queue))
	{	dlQueue(queue, e);
		bt = &e;
		cout << bt->e << " ";
		if(bt->lchild)enQueue(queue, *bt->lchild);
		if(bt->rchild)enQueue(queue, *bt->rchild);
	}
}//层次遍历
int main()
{
	Queue queue;
	InitializeQueue(queue,20);
	ofstream OutFile("Test.txt"); 
	OutFile << "ABC##DE#G##F###";  
	OutFile.close();
	ifstream readFile("Test.txt");
	char temp[1024] = { 0 };
	readFile >> temp; // 利用文件读入二叉树,方便反复测试
	readFile.close();
	T* bt=0;
	bt=CreatTree(bt,temp);
	Preorder(bt);
	cout << '\n';
	Midorder(bt);
	cout << '\n';
	Lasorder(bt);
	cout << '\n';
	layer(bt, queue);

}

你可能感兴趣的:(数据结构,二叉树,数据结构,c++)