结点是数字,采用数组存储树,使用后序序列和中序序列,还原创建二叉树,并用前序序列验是否创建成功。
仍然是三步:1、前序(后序)找根;2、中序分左右;3、还原创建
代码实现:
#include <iostream>
using namespace std;
#include <string>
#define max_size 100
int root;
int n;
int lch[max_size], rch[max_size];
int mid[max_size], post[max_size];
void Input(int* arr)
{
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
}
char CreateTree(int mid_start, int post_start, int len)
{
if (len <= 0)
{
return 0;
}
int r = post[post_start + len - 1]; //后序找根
int loc = 0;
while (mid[mid_start + loc] != r)
{
loc++;
} //中序分左右
lch[r] = CreateTree(mid_start, post_start, loc); //递归创建左子树
rch[r] = CreateTree(mid_start + loc + 1, post_start + loc, len - loc - 1); //递归创建右子树
return r;
}
void Preorder(int root)
{
cout << root << " ";
if (lch[root])
{
Preorder(lch[root]);
}
if (rch[root])
{
Preorder(rch[root]);
}
}
int main()
{
cout << "请输入元素个数" << endl;
cin >> n;
cout << "请输入中序序列" << endl;
Input(mid);
cout << "请输入后序序列" << endl;
Input(post);
root = CreateTree(0, 0, n);
cout << "前序遍历序列为" << endl;
Preorder(root);
cout << endl;
return 0;
}