二叉树的创建
方法一:给定二叉树的数组元素序列和大小创建二叉树
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 = Buynode();
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 = Buynode();
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 = Buynode();
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 = Buynode();
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 = 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);
}//根据前序遍历和后序遍历创建二叉树 (前序和后续不能唯一确定一种二叉树)
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;
BtNode *s = Buynode();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;}
二叉树_二叉树的创建
最新推荐文章于 2020-05-28 15:37:02 发布