二叉查找树(binary search tree)详解

二叉查找树(Binary Search Tree),也称二叉排序树(binary sorted tree),是指一棵空树或者具有下列性质的二叉树:

  • 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值
  • 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值
  • 任意节点的左、右子树也分别为二叉查找树
  • 没有键值相等的节点(no duplicate nodes)

本文地址:http://www.cnblogs.com/archimedes/p/binary-search-tree.html,转载请注明源地址。

二叉查找树相比于其他数据结构的优势在于查找、插入的时间复杂度较低。为O(log n)。

二叉查找树是基础性数据结构,用于构建更为抽象的数据结构,如集合、multiset、关联数组等。

二叉查找树的查找过程和次优二叉树类似,通常采取二叉链表作为二叉查找树的存储结构。中序遍历二叉查找树可得到一个关键字的有序序列,一个无序序列可以通过构造一棵二叉

查找树变成一个有序序列,构造树的过程即为对无序序列进行查找的过程。每次插入的新的结点都是二叉查找树上新的叶子结点,在进行插入操作时,不必移动其它结点,只需改动

某个结点的指针,由空变为非空即可。搜索,插入,删除的复杂度等于树高,期望O(log n),最坏O(n)(数列有序,树退化成线性表).

虽然二叉查找树的最坏效率是O(n),但它支持动态查询,且有很多改进版的二叉查找树可以使树高为O(logn),如:SBT,AVL,红黑树等.故不失为一种好的动态查找方法.

基本操作实现:

1、二叉查找树声明

/*********二叉查找树声明 ********/
typedef struct tree_node *tree_prt;
struct tree_node {
    element_type element;
    tree_ptr left;
    tree_prt right;
};
typedef tree_ptr SEARCH_TREE;

2、查找操作

思路:若根结点的关键字等于查找的关键字,查找成功;否则,若小于根结点的关键字的值,递归查找左子树,否则若大于根结点的关键字的值,递归查找右子树,若子树为空,则查找不成功

/*********查找算法 ********/
tree_ptr find(element_type x, SEARCH_TREE T)
{
    if(T ==NULL)
        return NULL;
    if(x < T->element)
        return (find(x, T->left));
    else if(x > T->element)
        return (find(x, T->right));
    else
        return T;
}

3、查找最大最小结点

/*********查找最大最小结点 ********/
tree_ptr find_min(SEARCH_TREE T)  //递归
{
    if(T == NULL)
        return NULL;
    else if(T->left == NULL)
        return T;
    else
        return find_min(T->left);
}
tree_ptr find_max(SEARCH_TREE T)  //非递归
{
    if(T != NULL) {
        while(T->right != NULL) {
            T = T->right;
        }
    }
    return T;
}

4、插入操作

思路:首先执行查找算法,找出被插入结点的父结点,判断被查结点是父结点的左孩子还是右孩子,将被插结点作为叶子结点插入,若二叉树为空,则首先单独生成根结点

/*********插入结点1 ********/
void insert(element_type x, SEARCH_TREE *T)
{
    if(*T == NULL) {  /* 空树 */
        *T = (SEARCH_TREE)malloc(sizeof(struct tree_node));
        if(*T == NULL) {
            printf("Out of space!!!");
            return;
        } else {
            (*T)->element = x;
            (*T)->left = (*T)->right = NULL;
        }
    } else if(x < (*T)->element) {
        insert(x, &((*T)->left));
    } else {
        insert(x, &((*T)->right));
    }
}

当然也可以使用返回插入结点的方式:

/*********插入结点2 ********/
tree_ptr insert(element_type x, SEARCH_TREE T)
{
    if(T == NULL) {  /* 空树 */
        T = (SEARCH_TREE)malloc(sizeof(struct tree_node));
        if(T == NULL) {
            printf("Out of space!!!");
            return;
        } else {
            T->element = x;
            T->left = T->right = NULL;
        }
    } else if(x < T->element) {
        T->left = insert(x, T->left));
    } else {
        T->right = insert(x, T->right));
    }
    return T;
}

5、删除操作

在二叉查找树删去一个结点,分三种情况讨论:

①  若p是叶子结点: 直接删除p,如图(b)所示。

②  若p只有一棵子树(左子树或右子树):直接用p的左子树(或右子树)取代p的位置而成为f的一棵子树。即原来p是f的左子树,则p的子树成为f的左子树;原来p是f的右子树,则p的子树成为f的右子树,如图(c)、 (d)所示。

③ 若p既有左子树又有右子树 :处理方法有以下两种,可以任选其中一种。

◆  用p的直接前驱结点代替p。即从p的左子树中选择值最大的结点s放在p的位置(用结点s的内容替换结点p内容),然后删除结点s。s是p的左子树中的最右边的结点且没有右子树,对s的删除同②,如图(e)所示。

◆ 用p的直接后继结点代替p。即从p的右子树中选择值最小的结点s放在p的位置(用结点s的内容替换结点p内容),然后删除结点s。s是p的右子树中的最左边的结点且没有左子树,对s的删除同②。

void delete(SEARCH_TREE *p)
{
    SEARCH_TREE q, s;
    if((*p)->right == NULL) {
        q = *p;
        *p = (*p)->left;
        free(q);
    } else if((*p)->left == NULL) {
        q = *p;
        *p = (*p)->right;
        free(q);
    } else {
        q = *p;
        s = (*p)->left;
        while(s->right != NULL) {
            q = s;
            s = s->right;
        }
        (*p)->element = s->element;
        if(q != p) {
            q->right = s->left;
        } else {
            q ->left = s->left;
        }
    }
    free(s);
}
void deleteBST(SEARCH_TREE *T, element_type key)
{
    if(!(*T)) {
        return;
    } else if ((*T)->element == key) {
        free(*T);
    } else if((*T)->element > key) {
        deleteBST((*)T->left, key);
    } else {
        deleteBST((*)T->right, key);
    }
}

编程实践

poj2418 Hardwood Species

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct node {
    char name[31];
    struct node *lchild, *rchild;
    int count;
}tree;
struct node *root;
int n = 0;
void mid_cal(struct node *root)
{
    if(root != NULL) {
        mid_cal(root->lchild);
        printf("%s %.4lf\n", root->name, ((double)(root->count) / (double)n) * 100.0);
        mid_cal(root->rchild);
    }
}

void insertBST(struct node** root, char *s)
{
    if(*root == NULL) {
        struct node *p = (struct node*)malloc(sizeof(tree));
        strcpy(p->name, s);
        p->lchild = p->rchild = NULL;
        p->count = 1;
        *root = p;
    } else {
        if(strcmp(s, (*root)->name) == 0) {
            ((*root)->count)++;
            return;
        } else if(strcmp(s, (*root)->name) < 0) {
            insertBST(&((*root)->lchild), s);
        } else {
            insertBST(&((*root)->rchild), s);
        }
    }
}

int main()
{
    char s[31];
    while(gets(s)) {
        insertBST(&root, s);
        n++;
    }
    mid_cal(root);
    return 0;
}

参考资料

1、Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein(潘金贵等译)《算法导论》. 机械工业出版社.

2、ACM/ICPC 算法训练教程

3、《数据结构》严蔚敏、吴伟民

4、维基百科

二叉查找树(binary search tree)详解

时间: 2024-08-06 00:36:27

二叉查找树(binary search tree)详解的相关文章

二叉查找树(binary search tree)

二叉查找树的性质:对于树中的每个节点x,它的左子树中所有项的值不大于x的值,它的右子树中所有项的值不小于x的值. 二叉查找树应具有以下操作 ① 寻找最小项 FIND_MIN ② 寻找最大项 FIND_MAX ③ 是否包含 CONTAINS ④ 树是否为空 IS_EMPTY ⑤ 清空树 MAKE_EMPTY ⑥ 插入节点 INSERT ⑦ 移除节点 REMOVE ⑧ 打印树 PRINT_TREE (中序遍历) ⑨ 深拷贝 DEEP_CLONE 二叉查找树(binary search tree)的抽

【LeetCode】二叉查找树 binary search tree(共14题)

链接:https://leetcode.com/tag/binary-search-tree/ p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [220]Contains Duplicate III [315]Count of Smaller Numbers After Self [327]Count of Range Sum [352]Data Stream as Disjoint Intervals [493]

lintcode 容易题:Insert Node in a Binary Search Tree 在二叉查找树中插入节点

题目:  在二叉查找树中插入节点 给定一棵二叉查找树和一个新的树节点,将节点插入到树中. 你需要保证该树仍然是一棵二叉查找树.  样例 给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的: 挑战 能否不使用递归? 解题: 递归的方法比较简单 Java程序: /** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public

[leetcode] Validate Binary Search Tree (检验是否为二叉查找树) Python

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys

二叉查找树——A1064.Complete Binary Search Tree(30) 构建完全二叉查找树,利用完全二叉查找树的性质:左孩子为2x ,右孩子为 2x + 1

#include <bits/stdc++.h> #include <stdio.h> #include <stdlib.h> #include <queue> using namespace std; const int maxn = 1010; int temp[maxn],initial[maxn],n; int ind; void inorder(int root){//中序遍历 if(root > n){ return; } inorder(

【LeetCode】Validate Binary Search Tree 二叉查找树的判断

题目: Given a binary tree, determine if it is a valid binary search tree (BST). 知识点:BST的特点: 1.一个节点的左子树的所有点都小于或等于这个点的值,右子树的所有节点的值大于该节点的值: 2.最左节点值最小,最右节点值最大: 3.中序遍历结果值是一个非降的数列 问题:如果用Integer.MAX_VALUE会过不了测试用例,可是按照TreeNode中的定义,val值也是int呀,没办法用了Long,如果谁知道,麻烦

132.Find Mode in Binary Search Tree(二分搜索树的众数)

题目: Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. 给定具有重复项的二叉搜索树(BST),找到给定BST中的所有众数(最频繁出现的元素). Assume a BST is defined as follows: 假设BST定义如下: The left subtree of a node

【Recover Binary Search Tree】cpp

题目: Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? confused what "{1,#,2,3}&

leetcode笔记:Validate Binary Search Tree

一. 题目描写叙述 Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes