# 二叉树_二叉树的创建

BtNode * CreateBin(ElemType *ar,int left,int right);
BtNode * CreateBinary(ElemType *ar,int n)
{
if(NULL == ar || n < 1)
return NULL;
else
return CreateBin(ar,0,n-1);
}
BtNode * CreateBin(ElemType *ar,int left,int right)
{
BtNode *s = NULL;
if(left <= right)
{
int mid = (right - left + 1)/2 + left;
s->data = ar[mid];
s->leftchild = CreateBin(ar,left,mid-1);
s->rightchild = CreateBin(ar,mid+1,right);
}
return s;
}
BtNode * CreateBinary(ElemType *ar,int n)
{
if(NULL == ar || n < 1)
return NULL;
else
return CreateBin(ar,0,n-1);
}

BtNode * CreateTree(ElemType *&str)
{
BtNode *s = NULL;
if(NULL != str && *str != END)
{
s->data = *str;
s->leftchild = CreateTree(++str);
s->rightchild = CreateTree(++str);
}
return s;
}

BtNode * CreateTree1()
{
BtNode *s = NULL;
ElemType item;
cin>>item;
if(item != '#')
{
s->data = item;
s->leftchild = CreateTree1();
s->rightchild = CreateTree1();
}
return s;
}

//根据前序遍历和中序遍历创建二叉树
BtNode * CreatePI(ElemType *ps,ElemType *is,int n);
BtNode * CreateTreePI(ElemType *ps,ElemType *is,int n)
{
if(NULL == ps || NULL == is || n < 1)
return NULL;
else
return CreatePI(ps,is,n);
}
BtNode * CreatePI(ElemType *ps,ElemType *is,int n)
{
BtNode *s = NULL;
if(n > 0)
{
s->data = ps[0];
int pos = FindPos(is,ps[0],n);
if(pos == -1) exit(1);
s->leftchild = CreatePI(ps+1,is,pos);
s->rightchild = CreatePI(ps+pos+1,is+pos+1,n - pos - 1);
}
return s;
}

//根据中序遍历和后序遍历创建二叉树
BtNode * CreateIL(ElemType *is,ElemType *ls,int n);
BtNode * CreateTreeIL(ElemType *is,ElemType *ls,int n)
{
if(NULL == is || NULL == ls || n < 1)
return NULL;
else
return CreateIL(is,ls,n);
}
BtNode * CreateIL(ElemType *is,ElemType *ls,int n)
{
BtNode *s = NULL;
if(n > 0)
{
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);
}

//根据前序遍历和后序遍历创建二叉树  （前序和后续不能唯一确定一种二叉树）
BtNode * CreatePL(ElemType *ps,ElemType *ls,int pstat ,int pend ,int lstat ,int lend);
BtNode * CreateTreePL(ElemType *ps,ElemType *ls,int n)
{
if(NULL == ps || NULL == ls || n < 1)
return NULL;
else
return CreatePL(ps,ls,0,n-1,0,n-1);
}
BtNode * CreatePL(ElemType *ps,ElemType *ls,int pstat ,int pend ,int lstat ,int lend)
{
if(pstat>pend || lstat>lend)
return NULL;

s->data = ps[pstat];
if(pstat +1 >pend)
return s;
int val = ps[pstat +1];
int index = lstat;
for(;index <pend && ls[index]!=val;index++);
int length = index-lstat;
s->leftchild = CreatePL(ps,ls,pstat+1,pstat+1+length ,lstat ,index);
s->rightchild = CreatePL(ps,ls,pstat+length+2,pend ,index+1 ,lend-1);
return s;}

03-20 2793
02-12 144
11-25
04-19
12-28 240
12-05
08-17
12-24
06-11 706
11-23 99