设计一个程序,由给定的二叉树先序序列,建立其二叉链表存储结构,并求出二叉树的中序序列和后序序列。
#include<iostream>//蓝多多算法实验五:二叉树的应用(一)
#include<stdio.h>
#include<malloc.h>
#include<iomanip>
using namespace std;
typedef char ElemType;
typedef struct Bnode
{
ElemType data;
struct Bnode* LChild, * RChild;
} BNode, * BTree;
void InitList(BTree &BT)//初始化
{
BT = NULL;
}
void preCreateBTree(BTree& BT)
{
char data;
data = getchar();
if (data == '#') BT = NULL;
else
{
BT = (BTree)malloc(sizeof(Bnode));
BT->data = data;
preCreateBTree(BT->LChild);
preCreateBTree(BT->RChild);
}
}
void PreOrder(BTree bt)//先序遍历
{
if (bt != NULL)
{
cout<< bt->data<<setw(3);
PreOrder(bt->LChild);
PreOrder(bt->RChild);
}
}
void InOrder(BTree bt)//中序遍历
{
if (bt!= NULL)
{
InOrder(bt->LChild);
cout<< bt->data<<setw(3);
InOrder(bt->RChild);
}
}
void PostOrder(BTree bt)//后序遍历
{
if (bt != NULL)
{
PostOrder(bt->LChild);
PostOrder(bt->RChild);
cout<< bt->data<<setw(3);
}
}
int main()
{
BTree bt;
cout << "二叉树初始化中......" << endl;
InitList(bt);
cout << "请输入给定的二叉树先序序列" << endl;
preCreateBTree(bt);
cout << "给定的二叉树先序序列为:" << endl;
PreOrder(bt);
cout << endl;
cout << "二叉树的中序序列结果为" << endl;
InOrder(bt);
cout << endl;
cout << "二叉树的后序序列结果为" << endl;
PostOrder(bt);
cout << endl;
system("pause");
}
运行结果: