Binary Search Tree是数据结构中比较有用的一种二叉树结构,这种结构讲大量的数据进行平摊式分布,并且规定大的数在右边,小的数在左边,以这种方式存放的数据可以非常方便地做数据排序和检索。
关于BST的更多信息,可以查看这个链接(英文,讲的非常好,不得不赞):http://algs4.cs.princeton.edu/32bst/
台湾国立清华大学韩永楷老师的MOOC(讲的超级棒,完爆国内,我的代码实现就是参考韩老师的课程内容):http://www.icourse163.org/course/NTHU-451013#/info
下面给出使用C语言的实现方式,我使用了最简单的方式实现,代码中有很多注释,大家可以参考。代码可编译,可运行。
/*************************************************************************
> File Name: bst.c
> Author: Baniel Gao
> Mail: createchance@163.com
> Created Time: Thu 01 Dec 2016 08:29:23 AM EST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
typedef struct node_t {
int key;
struct node_t* parent;
struct node_t* left;
struct node_t* right;
} node;
/*
* Get min number of this tree pointed by root.
*
* Return min node pointer, NULL if root is NULL.
*/
node* min(node* root)
{
node* min_node = root;
if (root == NULL) {
return NULL;
}
while (min_node->left != NULL) {
min_node = min_node->left;
}
return min_node;
}
/*
* Get max number of this tree pointed by root.
*
* Return max node pointer, NULL if root is NULL.
*/
node* max(node* root)
{
node* max_node = root;
if (root == NULL)
{
return NULL;
}
while (max_node->right != NULL)
{
max_node = max_node->right;
}
return max_node;
}
/*
* Search the number k.
*
* Return node pointer which contains the key, NULL if do not match anything.
*/
node* search(node* root, int k)
{
node* current = root;
if (root == NULL) {
return NULL;
}
while (1) {
if (current->key == k) {
break;
} else if (current->key > k) {
current = current->left;
} else {
current = current->right;
}
if (current == NULL) {
break;
}
}
return current;
}
/*
* Find the predeccessor of k.
*
* Return node pointer of predeccessor if success, NULL if find nothing.
*/
node* predecessor(node* root, int k)
{
if (root == NULL)
{
return NULL;
}
node* target = search(root, k);
if (target != NULL) {
if (target->left != NULL) {
target = max(target->left);
} else {
while (1) {
if (target->parent == NULL) {
target = target->parent;
break;
} else if (target == target->parent->right) {
target = target->parent;
break;
} else if (target == target->parent->left) {
target = target->parent;
}
}
}
}
return target;
}
/*
* Find successor of number k.
*
* Return node pointer of successor if success, NULL if find nothing.
*/
node* successor(node* root, int k)
{
if (root == NULL) {
return NULL;
}
node* target = search(root, k);
if (target != NULL) {
if (target->right != NULL) {
target