二叉搜索树(Binary Search Tree):左子树上的值都小于根结点,右子树上的值都大于根结点,其中序遍历即为有序序列。
测试结果:
15
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14
9
1 2 3 4 5 6 7 8 10 11 12 13 14
4
1 2 3 5 6 7 8 10 11 12 13 14
6
1 2 3 5 7 8 10 11 12 13 14
13
1 2 3 5 7 8 10 11 12 14
3
1 2 5 7 8 10 11 12 14
5
1 2 7 8 10 11 12 14
14
1 2 7 8 10 11 12
12
1 2 7 8 10 11
11
1 2 7 8 10
10
1 2 7 8
2
1 7 8
7
1 8
1
8
8
代码:
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstdlib>
using namespace std;
typedef struct BST {
int data;
BST* lchild, * rchild;
}BSTNode,*BSTree;
bool BST_Insert(BSTree& T, int data)
{
if (T == NULL)
{
T = new BSTNode;
T->data = data;
T->lchild = T->rchild = NULL;
return true;
}
else if (data < T->data) {
return BST_Insert(T->lchild, data);
}
else if (data > T->data) {
return BST_Insert(T->rchild, data);
}
else // 已存在值不插入
return false;
}
BSTree BST_Dele(BSTree& T, int data)
{
if (T == NULL) return NULL;
if (T->data == data)
{
BSTree p, q; // 前驱 后继
//如果左右儿子都有比较难删除
if (T->lchild && T->rchild)
{
p = T;
q = p->lchild;
while (q->rchild) // 寻找左子树最大
{
p = q;
q = q->rchild;
}
T->data = q->data;
if (p != T) {
p->rchild = q->lchild;
}
else {
p->lchild = q->lchild;
}
free(q);
}
else if (T->lchild) { //只有左儿子
p = T;
T = T->lchild;
free(p);
}
else //只有右儿子或左右儿子都没有(叶子)
{
p = T;
T = T->rchild;
free(p);
}
}
else if (data < T->data) {
T->lchild = BST_Dele(T->lchild, data);
}
else if (data > T->data) {
T->rchild = BST_Dele(T->rchild, data);
}
return T;
}
//BST 前序遍历
void Prior_Order(BSTree& T)
{
if (T != NULL) {
cout << T->data<<' ';
Prior_Order(T->lchild);
Prior_Order(T->rchild);
}
}
//BST 中序遍历
void Mid_Order(BSTree& T)
{
if (T != NULL) {
Mid_Order(T->lchild);
cout << T->data<<' ';
Mid_Order(T->rchild);
}
}
//BST 后序遍历
void Post_Order(BSTree& T)
{
if (T != NULL) {
Post_Order(T->lchild);
Post_Order(T->rchild);
cout << T->data<<' ';
}
}
int main()
{
ios::sync_with_stdio(false);
BSTree T = NULL;
for (int i = 5; i <= 10; i++) {
BST_Insert(T, i);
}
for(int i=0;i<5;i++){
BST_Insert(T, i);
}
for(int i=10;i<=15;i++){
BST_Insert(T, i);
}
//测试删除
while(T!=NULL){
int t;
cin>>t;
BST_Dele(T,t);
Mid_Order(T);
cout<<endl;
}
return 0;
}