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 * CreateTree2(ElemType *&str)
{
BtNode *s = NULL;
if(NULL != str && *str != END)
{
s = Buynode();
s->data = *str;
s->leftchild = CreateTree2(++str);
s->rightchild = CreateTree2(++str);
}
return s;
}
先序遍历可以确定出树的根节点即第一个元素就是根节点,中序遍历可以确定左子树和右子树,接下来依次递归,直到区间的个数<=0就能确定出这棵树
BtNode * Buynode()
{
BtNode *s = (BtNode*)malloc(sizeof(BtNode));
if(NULL == s) exit(1);
memset(s,0,sizeof(BtNode)); // new;
return s;
}
int FindPos(ElemType *is,ElemType x,int n)
{
int pos = -1;
for(int i = 0;i<n;++i)
{
if(is[i] == x)
{
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];
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 * CreateTreePI(ElemType *ps,ElemType *is,int n)
{
if(NULL == ps || NULL == is || n < 1)
return NULL;
else
return CreatePI(ps,is,n);
}
后续遍历可以确定出树的根节点即最后一个元素就是根节点,中序遍历可以确定左子树和右子树,接下来依次递归,直到区间的个数<=0就能确定出这棵树
BtNode * Buynode()
{
BtNode *s = (BtNode*)malloc(sizeof(BtNode));
if(NULL == s) exit(1);
memset(s,0,sizeof(BtNode)); // new;
return s;
}
int FindPos(ElemType *is,ElemType x,int n)
{
int pos = -1;
for(int i = 0;i<n;++i)
{
if(is[i] == x)
{
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);
}