整体思路使用递归,顺序考察先序序列创建根节点,同时左右向对中序序列进行划分 #include
#include
typedef struct BTree{
int num;
struct BTree *lc,*rc;
}BTree;
int k; //标记下个访问的先序结点位置
void CreateBTree(BTree *T,int ordp[],int ordi[],bool visited[],int locate,int n){
if (visited[locate] || locate>=n || locate<0)
return;
else {
visited[locate]=true;
int l;
//在中序序列中向当前根节点左侧探查,考虑是否生成左子树
for (l=locate-1; l>=0 && !visited[l]; l--) {
if (ordi[l]==ordp[k+1]) {
BTree *t=(BTree*)malloc(sizeof(BTree));
t->num=ordp[++k];
t->lc=NULL;
t->rc=NULL;
T->lc=t;
CreateBTree(T->lc, ordp, ordi, visited, l, n);
break;
}
}
//在中序序列中向当前根节点右侧探查,考虑是否生成右子树