二叉树的建立

二叉树建立方法:
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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值