二叉查找树【链表法】

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;
}

 

posted @ 2020-10-29 20:50  ctxcc  阅读(117)  评论(0)    收藏  举报