二叉树创建(错误分享,开心一下),及删除(重点内容)

由于要面对考试,重写一下二叉树的构建,结果各种出错,整理一下

前期我陷入对指针应用的迷惑。
错误及其离谱
例如:

void CreateTree(tree *&root,int n)
{
    while (root)
        root=root->child[n>root->power];//明明使用了引用,却一直在改变root值,
        //显然会导致主函数中的root指向发生改变,
        //我却还傻傻的以为用了个骚操作root->child[n>root->power],很牛逼的样子
        //真是个逗比。
    Bound(root,n);
}

后期逐渐意识到引用的使用及自己理解的错误
开始用递归,不过还是错误百出。
敲码累了的同学,可以开心一下。

  1. 第一种
void Bound(tree *& root,int n)
{
    root=(tree *)malloc(sizeof(tree));
    root->power=n;
    root->child[0]=root->child[1]=0;
}//上面那个函数没错主要在CreateTree中
void CreateTree(tree *&root,int n)
{
    while(root)//不知道咋想的,循环,加递归,后面还有一个操作,这三行错的真是秀。
    CreateTree(root->child[n>root->power],n);
    Bound(root,n);
}
  1. 第二种
  while(root)//加了个if,可循环加递归,依旧在那里,真是无语
    CreateTree(root->child[n>root->power],n);
    if (root==NULL)
    Bound(root,n);
  1. 第三种
 if (root==NULL)//好不容易改对了
        Bound(root,n);
    else
    CreateTree(root->child[n>root->power],n);

二叉排序树的删除操作

void DeleteTreeNode(tree *&root,int n)
{
    tree *te=root;
    //首先找到要被删除的节点
    while(te->child[n>te->power]->power!=n&&te!=NULL)
        te=te->child[n>te->power];
        //跳出循环,得到节点,到底是不是还要判断一下
    if (te==NULL)
        return;
    else
    {
        tree *te2=te->child[n>te->power];//te2位于将被删除的节点。
        //开始删除操作。
        //分为四种情况
        //第一种,te2的左右子树均为空
        if (te2->child[0]==NULL&&te2->child[1]==NULL)
            delete(te2);
        //第二种情况,te2左子树为空,右子树存在
        else if (!te2->child[0])
            te->child[n>te->power]=te2->child[1];
            //第三种,te2右子树为空,左子树存在
        else if (!te2->child[1])
            te->child[n>te->power]=te2->child[0];
            //第四种,te2左右子树都存在。
        else
        {
            tree *te3=te2->child[0];
            //找到将要被删除左子树的最大值,换到被删除节点上去
            while(te3->child[1]!=NULL)
            {
                te2=te3;
                te3=te3->child[1];
            }
            te->child[n>te->power]->power=te3->power;
            if (te2==te->child[n>te->power])
                te2->child[0]=te3->child[0];
            else
                te2->child[1]=te3->child[0];
            delete(te3);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值