【要求】
设计一个程序,根据二叉树的先根序列和中根序列创建一棵用左右指针表示的二叉树
【代码】
#include <iostream>
using namespace std;
/*-------------------------二叉树的链式存储---------------------------*/
typedef struct BiTNode
{
char data; //结点数据域
BiTNode *lchild, *rchild; //左右孩子指针
}*BiTree;
/*---------------------------二叉树的遍历-----------------------------*/
//二叉树的中序遍历
void MidOrder(BiTree T)
{
if (T)
{
MidOrder(T->lchild);
cout << T->data << " ";
MidOrder(T->rchild);
}
}
//二叉树的先序遍历
void PreOrder(BiTree T)
{
if (T)
{
cout << T->data << " ";
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
//二叉树的后序遍历
void PostOrder(BiTree T)
{
if (T)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
cout << T->data << " ";
}
}
/*--------------------------先序和中序构造二叉树--------------------------*/
/* i是先序序列首字符在a[]中的位置
j是中序序列首字符在b[]中的位置
len是子树的字符长度
*/
BiTree CreatTree(char a[], char b[], int i,int j, int len)
{
BiTree root = new BiTNode; //二叉树的根结点
if (len <= 0) return NULL;
else {
root->data = a[i];
char *p = b;
for (p = b; p != NULL; p++) //在b中找到a[i]
{
if (*p == a[i]) break;
}
int m = p - b; //计算该结点在b中的下标
root->lchild = CreatTree(a, b, i + 1, j, m - j); //左孩子
root->rchild = CreatTree(a, b, i + (m - j) + 1, m + 1, len - 1 - (m - j)); //右孩子
return root; //返回二叉树的根
}
}
int main()
{
char a[] = "ABDHLEKCFG"; //"ABDGCEF"; //先序
char b[] = "HLDBEKAFCG"; //"DGBAECF"; //中序
int n = strlen(a); //结点个数
BiTree node = NULL;
node = CreatTree(a, b, 0, 0, n); //先序和中序构造二叉树
cout << "先序遍历输出:";
PreOrder(node); //先序遍历输出
cout << endl;
cout << "中序遍历输出:";
MidOrder(node); //中序遍历输出
cout << endl;
cout << "后序遍历输出:";
PostOrder(node); //后序遍历输出
cout << endl;
return 0;
}