首页 > 其他 > 详细

搜索二叉树

时间:2015-11-22 21:39:43      阅读:243      评论:0      收藏:0      [点我收藏+]

//二叉查找树的实现
#include <cstdio>
#include <cstdlib>
//#define _OJ_

typedef struct tree1
{
    int data;
    struct tree1 *lchild;
    struct tree1 *rchild;
} tree1, *tree;

tree
find(int x, tree T)
{
    if(T == NULL)
        return NULL;
    if(x < T->data)
        find(x, T->lchild);
    else
    if(x > T->data)
        find(x, T->rchild);
    else
        return T;
}

tree
find_min(tree T)
{

    // printf("fsaf\n");
    if(T == NULL)
        return NULL;
    else
        if(T->lchild == NULL)
            return T;
    else
        find_min(T->lchild);
}

tree
find_max(tree T)
{
    if(T != NULL)
        while(T->rchild != NULL)
            find_max(T->rchild);
     return T;
}

tree
insert(int x, tree T)
{
    // printf("dfsad\n");
    if(T == NULL)
    {
     T = (tree) malloc (sizeof(tree1));
     T->data = x;
     T->lchild = T->rchild = NULL;
    }
    else
    if(x < T->data)
        T->lchild = insert(x,T->lchild);
    else
    if(x > T->data)
        T->rchild = insert(x,T->rchild);
    return T;
}


tree
del_tree(int x, tree T)
{//找出右子树最小的代替要删除的节点,再删除最小的那个节点!!!
    tree tmp;
    if(T == NULL)
        return NULL;
    else
        if(x < T->data)
            T->lchild = del_tree(x,T->lchild);
    else
        if(x > T->data)
            T->rchild = del_tree(x,T->lchild);
    else                                     //find element to del_tree
        if(T->lchild && T->rchild)//two children
        {
        tmp = find_min(T);
        T->data = tmp->data;
        T->rchild = del_tree(T->data, T->rchild);
        }
        else    //one or zero child
        {
        tmp = T;
        if(T->lchild == NULL)
            T = T->rchild;
        else if(T->rchild == NULL)
            T = T->lchild;printf("%p\n", T);
            // free(tmp);
        }
        return T;
}

int main(int argc, char const *argv[]) {
#ifndef _OJ_  //ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
#endif
    int i,n;
    int a[10];
    tree T = NULL;
    tree T1 = NULL;
    tree T2 = NULL;
    scanf("%d", &n);
    for(i = 0;i < n; i++)
    {
    scanf("%d", &a[i]);
    printf("%d\n", a[i]);
    }
    T = insert(a[0], T);
    printf("T == %p\n", T);
    insert(a[1],T);

    T1 = find_min(T);
    printf("T! == %p\n", T1);
    printf("%d\n", T1->data);
    del_tree(0,T);
    printf("%p\n", T->lchild);
    T2 = find_min(T);
    printf("%d\n", T2->data);
    return 0;
}

 

搜索二叉树

原文:http://www.cnblogs.com/airfand/p/4986686.html

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