首页 > 其他 > 详细

二叉查找树【链表法】

时间:2020-10-29 21:57:51      阅读:32      评论:0      收藏:0      [点我收藏+]

find、insert、delete、先序遍历操作

typedef struct node stree;

struct node
{
    int val;
    stree *left;
    stree *right;
};

stree *T;

stree* MakeEmpty(stree *t)
{
    if (t != NULL)
    {
        MakeEmpty(t -> left);
        MakeEmpty(t -> right);
        free(t);
    }
    return NULL;
}

stree* inst(int x, stree *t)    // 递归插入
{
    if (t == NULL)
    {
        t = (struct node*) malloc(sizeof (struct node));
        t -> val = x;
        t -> left = t -> right = NULL;
        return t;
    }

    if (x < t -> val) t -> left = inst(x, t -> left);
    else if (x > t -> val) t -> right = inst(x, t -> right);

    return t;
}

stree* find(int x, stree *t)
{
    if (t == NULL) return NULL;

    if (x < t -> val) t = find(x, t -> left);
    else if (x > t -> val) t = find(x, t -> right);
    else    return t;
}

stree* findMin(stree *t)
{
    if (t == NULL) return NULL;

    if (t -> left == NULL) return t;
    else    return findMin(t -> left);
}

stree* findMax(stree *t)
{
    if (t == NULL) return NULL;

    while (t -> right != NULL)
        t = t -> right;

    return t;
}

void print(stree *t) // 先序遍历
{
    if (t == NULL) return;

    printf("%d ", t -> val);
    print(t -> left);
    print(t -> right);
}

stree* del(int x, stree *t)
{
    if (t == NULL)
        puts("Not Found!");
    else if (x < t -> val) t -> left = del(x, t -> left);
    else if (x > t -> val) t -> right = del(x, t -> right);

    // 拥有两个儿子
    else if (t -> left && t -> right)
    {

        stree* tmp;
        tmp = findMin(t -> right);
        t -> val = tmp -> val;
        del(tmp -> val, t -> right);
    }
    // 1个 or 0个儿子
    else
    {
        stree* tmp;
        tmp = t;
        if (t -> left == NULL) t = t -> right;
        else if (t -> right == NULL) t = t -> left;
        free(tmp);
    }

    return t;
}

int main()
{
    T = MakeEmpty(T);
    int n, x;
    cin >> n;

    for (int i = 0; i < n; i ++)
    {
        scanf("%d", &x);
        T = inst(x, T);
    }

    //print(T);
    //cout << find(8, T) << endl;
    //cout << findMin(T) << endl;
    //cout << findMax(T) << endl;
    //T = del(4, T);
    //print(T);

    return 0;
}

 

二叉查找树【链表法】

原文:https://www.cnblogs.com/ctxcc/p/13899137.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!