二叉树删除前面节点(C语言初始版)

#include <stdlib.h>
#include <stdio.h>
typedef struct node
{
    int key;
    struct node *left;
    struct node *right;
} Btree;

Btree *InsertBtree(Btree *t,int x)
{
    Btree *f = NULL,*p;
    p = t;
    while (p)
    {
        if (x == p->key)
            return t;
        f = p;
        if (x < p->key)
            p = p->left;
        else
            p = p->right;
    }
    p = (Btree *)malloc(sizeof(Btree));
    p->key = x;
    p->left = p->right = NULL;
    if (t == NULL)
        t = p;
    else
    {
        if (x < f->key)
            f->left = p;
        else
            f->right = p;
    }
    return t;
}

void DeleteBstree(Btree *t,int x)
{
    Btree *p = t;
    Btree *f = NULL;
    while (p != NULL)
    {
        if (x == p->key)
            break;
        else
        {
            f = p;
            p = (x < p->key) ? p->left : p->right;
        }
    }
    printf("\n%d ",p->key);
    printf("%d ",f->key);
    while (p != NULL)
    {
        if (p->left != NULL)
        {
            f = p->left;
            if (f->right != NULL)
            {
                p->key = f->right->key;
                p = f->right;
            }
            else
            {
                p->key = p->left->key;
                f = p;
                p = p->left;
            }
            continue;
        }
        else if (p->right != NULL)
        {
            if (f->left == p)
                f->left = p->right;
            else
                f->right = p->right;
            p->key = -1;
            p = NULL;

        }
        else
        {
            p->key = -1;
            p = NULL;
        }
    }
    return t;
}

Btree *CreateTree()
{
    Btree * t = NULL;
    int key;
    printf("\nPlease input a number until -1 endBye :\n");
    scanf("%d",&key);
    while (key != -1)
    {
        t = InsertBtree(t,key);
        scanf("%d",&key);
    }
    return t;
}

void Mid_order(Btree *t)
{
    if (t == NULL)
        return;
    else
    {
        Mid_order(t->left);
        if (t->key != -1)
        {
            printf("%d ",t->key);
        }
        Mid_order(t->right);
    }
}


int main()
{
    Btree *t;
    t = CreateTree();
    Mid_order(t);
    DeleteBstree(t,12);
    printf("\n");
    Mid_order(t);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值