BST树的基本实现
基本操作:创建,销毁,清空,增删改查,先中后层遍历。
都很简单,就是删除一个节点要分类讨论。
在一个二叉搜索树中,一个基本性质,左子树的所有节点小于根节点,右子树的所有节点大于等于根节点,依据这个性质讨论删除操作。
当被删除元素左子树为空、右子树为空,或者都为空,直接用左子树或者右子树替代。如删除15,设*root指向15这个节点
node* t = root;
root = root->rch;
free(t)
当左右子树都不空是,找到右子树的最小值k,更改root->data = k, 从右子树删除k,键值为k的节点左子树肯定为空,满足情况1.
node* p = root->rch;
while (p->lch)
{
p = p->lch;
}
root->data = p->data;
erase(root->rch, p->data) //递归
BST树完整代码如下
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
typedef struct node
{
int data;
node* lch;
node* rch;
}node;
void create(node** root)
{
*root = NULL;
}
void clean(node** root)
{
if (*root != NULL)
{
clean(&((*root)->lch));
clean(&((*root)->rch));
free(*root);
}
}
void destory(node** root)
{
clean(root);
}
void insert(node **root, int value)
{
if (*root == NULL)
{
node *temp = (node*)malloc(sizeof(node));
temp->lch = temp->rch = NULL;
temp->data = value;
*root = temp;
}
else
{
if ((*root)->data > value)
{
insert(&((*root)->lch), value);
}
else
{
insert(&((*root)->rch), value);
}
}
}
void input(node** root, int n)
{
clean(root);
for (int i = 0; i < n; i++)
{
int x;
scanf("%d", &x);
insert(root, x);
}
}
void pre_output(node *root)
{
if (root != NULL)
{
printf("%d ", root->data);
pre_output(root->lch);
pre_output(root->rch);
}
}
void post_output(node *root)
{
if (root != NULL)
{
post_output(root->lch);
post_output(root->rch);
printf("%d ", root->data);
}
}
void mid_output(node *root)
{
if (root != NULL)
{
mid_output(root->lch);
printf("%d ", root->data);
mid_output(root->rch);
}
}
void layer_output(node *root)
{
if (root == NULL) return;
queue<node*> q;
q.push(root);
while (!q.empty())
{
node *temp = q.front();
q.pop();
printf("%d ", temp->data);
if (temp->lch)
{
q.push(temp->lch);
}
if (temp->rch)
{
q.push(temp->rch);
}
}
}
node* find(node *root, int key)
{
if (root != NULL)
{
if (root->data == key)
{
return root;
}
else if (root->data > key)
{
return find(root->lch, key);
}
else
{
return find(root->rch, key);
}
}
return NULL;
}
void erase(node** root, int value)
{
if (*root != NULL)
{
if ((*root)->data == value)
{
if ((*root)->lch == NULL)
{
node* t = *root;
*root = (*root)->rch;
free(t);
}
else if ((*root)->rch == NULL)
{
node* t = *root;
*root = (*root)->lch;
free(t);
}
else
{
node *t = (*root)->rch;
while (t->lch != NULL)
{
t = t->lch;
}
(*root)->data = t->data;
erase(&((*root)->rch), t->data);
}
}
else if ((*root)->data > value)
{
erase(&((*root)->lch), value);
}
else
{
erase(&((*root)->rch), value);;
}
}
}
int main()
{
node *tree;
create(&tree);
input(&tree, 6);
pre_output(tree);
putchar(10);
destory(&tree);
return 0;
}