二叉搜索树的小结

一、什么是二叉搜索树

二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。

二、二叉搜索树的基本结构

typedef struct node* tree;
struct node {
    int element;
    struct node* left;
    struct node* right;
};

三、二叉搜索树的基本操作

1、 在二叉搜索树中插入结点

tree insert(tree t, int x) { 
    if(t == NULL){
        t = (struct node*)malloc(sizeof(struct node));
        t->element = x;
        t->right = t->left = NULL;
    } 
    else if(x < t->element) {
        t->left = insert(t->left, x);
    } 
    else if(x >= t->element) {
        t->right = insert(t->right,x);
    }
    return t;
}

2、二叉搜索树的遍历

a 先序遍历

void preorder(tree t){
    if(t == NULL) return ;
    else{
        pre[cnt++] = t->element;
        preorder(t->left);
        preorder(t->right);
    }
}

b 中序遍历

void inorder(tree t) {
    if(t == NULL) return ;
    else{
        inorder(t->left);
        in[cnt++] = t->element;
        inorder(t->right);
    }
}

c 后序遍历

void postorder(tree t) {
    if(t == NULL) return ;
    else{
        postorder(t->left);
        postorder(t->right);
        post[cnt++] = t->element;
    }
}

3、 在二叉搜索树中删除结点

void delete_BST(struct node **root, int element)
{
    struct node *p = *root;
    if(element == p->key)
    {

        if(p->lchild == NULL && p->rchild == NULL)
            *root = NULL;
        else if(p->lchild == NULL)
            *root = p->rchild;
        else if(p->rchild == NULL)
            *root = p->lchild;
        else
        {
            struct node *temp = p->rchild, *find = NULL;
            while(temp != NULL)
            {
                find = temp;
                temp = temp->lchild;
            }
            find->lchild = p->lchild;
            p = p->rchild;
            *root = p;
        }
    }
    if(element < p->key)
    {
        delete_BST(&p->lchild, element);
    }
    if(element > p->key)
    {
        delete_BST(&p->rchild, element);
    }
}

三、二叉搜索树的应用

主要用于排序和查找,会比较快。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值