#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int N = 100;
typedef struct node
{
char data;
struct node *lchild, *rchild;
}Node, *Tree;
char pre[N], in[N], post[N];
void Pre_Build(Tree &root, int preL, int preR, int inL, int inR)
{
if(preL > preR)
{
root = NULL;
return;
}
root = new Node;
root->data = pre[preL];
int k;
for(k = inL; k <= inR; k++)
if(in[k] == pre[preL])
break;
int num = k - inL;
Build(root->lchild, preL+1, preL+num, inL, k-1);
Build(root->rchild, preL+num+1, preR, k+1, inR);
}
void In_Build(Tree &root, int inL, int inR, int postL, int postR)
{
if(postL > postR)
{
root = NULL;
return;
}
root = new Node;
root->data = post[postR];
int k;
for(k = inL; k <= inR; k++)
if(in[k] == post[postR])
break;
int num = k - inL;
Build(root->lchild, inL, k-1, postL, postL+num-1);
Build(root->rchild, k+1, inR, postL+num, postR-1);
}
void Layer_Build(Tree &root, vector<char> layer, int inL, int inR)
{
if(layer.size() == 0)
{
root = NULL;
return;
}
root = new Node;
root->data = layer[0];
int k;
for(k = inL; k <= inR; k++)
if(in[k] == layer[0])
break;
vector<char> layerL;
vector<char> layerR;
for(int i = 1; i < layer.size(); i++)
{
bool left = false;
for(int j = 1; j < k; j++)
if(in[j] == layer[i])
{
left = true;
break;
}
if(left) layerL.push_back(layer[i]);
else layerR.push_back(layer[i]);
}
Build(root->lchild, layerL, inL, k-1);
Build(root->rhcild, layerR, k+1, inR);
}
已知前序或后序加上中序比较清晰简单,层序有点复杂,我没写出来,整理了一下,记住吧