一、利用先序遍历的结果创建
1:
void CreateTree4(BtNode *&ptr,ElemType *&str)
{
if(NULL == str || *str == '#')
{
ptr = NULL;
}
else
{
ptr = Buynode();
ptr->data = *str;
CreateTree4(ptr->leftchild,++str);
CreateTree4(ptr->rightchild,++str);
}
}
int main()
{
char *str="ABC##DE##F##G#H##";
BtNode *root = NULL;
CreateTree4(root,str);
return 0;
}
2:
BtNode * CreateTree1()
{
BtNode *s = NULL;
ElemType item;
cin>>item;
if(item != '#')
{
s = Buynode();
s->data = item;
s->leftchild = CreateTree1();
s->rightchild = CreateTree1();
}
return s;
}
int main()
{
BtNode *root = NULL;
root = CreateTree1();
return 0;
}
二、利用先序、中序遍历的结果创建二叉树:
int FindPos(ElemType *is,ElemType x,int n)
{
int pos = -1;
for(int i = 0;i<n;++i)
{
if(x == is[i])
{
pos = i;
break;
}
}
return pos;
}
BtNode * CreatePI(ElemType *ps,ElemType *is,int n) //前中序创建树
{
BtNode *s = NULL;
if(n > 0)
{
s = Buynode();
s->data = ps[0];// s->data = *ps;
int pos = FindPos(is,ps[0],n);
if(pos == -1) exit(1);
s->leftchild = CreatePI(ps+1,is,pos);
s->rightchild = CreatePI(ps+1+pos,is+1+pos,n - pos - 1);
}
return s;
}
BtNode * CreateTreePI(ElemType *ps,ElemType *is,int n) //前中序创建树
{
if(NULL == ps || NULL == is || n < 1)
return NULL;
else
return CreatePI(ps,is,n);
}
int main()
{
char *ps = "ABCDEFGH";
char *is = "CBEDFAGH";
char *ls = "CEFDBHGA";
int n = strlen(ps); // n = sizeof(ps);//
BtNode *root = NULL;
root = CreateTreePI(ps,is,n);
return 0;
}
三、利用中后序遍历创建二叉树
int FindPos(ElemType *is,ElemType x,int n)
{
int pos = -1;
for(int i = 0;i<n;++i)
{
if(x == is[i])
{
pos = i;
break;
}
}
return pos;
}
BtNode * CreateIL(ElemType *is,ElemType *ls,int n) //中后序创建树
{
BtNode *s = NULL;
if(n > 0)
{
s = Buynode();
s->data = ls[n-1];
int pos = FindPos(is,ls[n-1],n);
if(pos == -1) exit(1);
s->leftchild = CreateIL(is,ls,pos);
s->rightchild = CreateIL(is+pos+1,ls+pos,n - pos - 1);
}
return s;
}
BtNode * CreateTreeIL(ElemType *is,ElemType *ls,int n)//中后序创建树
{
if(NULL == is || NULL == ls || n < 1)
return NULL;
else
return CreateIL(is,ls,n);
}
int main()
{
char *ps = "ABCDEFGH";
char *is = "CBEDFAGH";
char *ls = "CEFDBHGA";
int n = strlen(ps); // n = sizeof(ps);//
BtNode* root = NULL;
root = CreateTreeIL(is,ls,n); //中后序
return 0;
}