二叉树建立方法:
1、以前序遍历输入,将“#”做为替代其没有左子树或者右子树的位置;
BtNode * CreateTree1()
{
BtNode *s = NULL;
ElemType item;
scanf("%c",&item);
if(item != '#')
{
s = Buynode();
s->data = item;
s->leftchild = CreateTree1();
s->rightchild = CreateTree1();
}
return s;
}
2、根据前序遍历和中序遍历创建二叉树;
前序:char *ps = “ABCDEFGH”;
中序:char *is = “CBEDFAGH”;
int FindIs(char *is,int n,ElemType x)
{
for(int i = 0;i<n;++i)
{
if(is[i] == x)
return i;
}
return -1;
}
BtNode * Create(char *ps,char *is,int n)
{
BtNode *s = NULL;
if(n > 0)
{
s = Buynode(); //创建一个新节点
s->data = ps[0]; //根节点为前序遍历第一个数据
int pos = FindIs(is,n,ps[0]); //找到根节点在中序遍历中的位置,将中序遍历从根节点处分成左子树和右子树
if(pos == -1) exit(1);
s->leftchild = Create(ps+1,is,pos); //将去掉根节点的前序遍历与中序遍历中根节点的左边结合建立左子树
s->rightchild = Create(ps+pos+1,is+pos+1,n-pos-1);//将去掉根节点和左子树数据的前序遍历和中序遍历中根节点右边的数据结合建立右子树
}
return s;
}
BtNode * CreatePI(char *ps,char *is)
{
if(ps == NULL || is == NULL)
{
return NULL;
}else
{
int n = strlen(ps);
return Create(ps,is,n);
}
}
3、根据中序和后序遍历创建树
中序:char *is = “CBEDFAGH”;
后序: char *ls = “CEFDBHGA”;
int FindIs(char *is,int n,ElemType x)
{
for(int i = 0;i<n;++i)
{
if(is[i] == x)
return i;
}
return -1;
}
BtNode * Create2(char *is,char *ls,int n)
{
BtNode *s = NULL;
if(n > 0)
{
int pos = FindIs(is,n,ls[n-1]); //在中序遍历中找出后序遍历最后一个数据即根节点的位置
if(pos == -1) exit(1);
s = Buynode();
s->data = ls[n-1];
s->leftchild = Create2(is,ls,pos); //中序遍历中根节点的左边和后序遍历
s->rightchild = Create2(is+pos+1,ls+pos,n-pos-1);//中序遍历中根节点的右边和后序遍历中右子树的部分
}
return s;
}
BtNode * CreateIL(char *is,char *ls,int n)
{
if(is == NULL || ls == NULL || n < 1)
return NULL;
else
return Create2(is,ls,n);
}