二叉排序树的基本操作:
1,添加一个节点。
2,删除一个节点。
这里说一下删除。
删除有3中情况:
1,没找到这个节点。
2,节点为叶子节点(没有左右孩子)。
3,节点只有左孩子。
4,节点只有右孩子。
5,左右孩子都有。又分两种情况(A和B)
情况A:节点的右孩子的左孩子为空。
情况B:一直找到节点的右孩子下左孩子为空的节点
上代码(C++):
/*
*二叉搜索树
*特点:各个节点的左子树比这个节点小右子树比这个节点大
*这里先不考虑两个节点相等的情况
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//宏定义
#define YES 1
#define NO 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int Status;
typedef int ElemType;
typedef struct TNode
{
ElemType data;
struct TNode * lchild;
struct TNode * rchild;
}TNode,*BSTree;
/**
*初始化树
*/
Status initBSTree(BSTree &bst)
{
bst = NULL;
return OK;
}
/*
*查询是否有这个节点
*若有:返回NULL;
*若无:返回应该插入的位置父节点;
*/
TNode* bst_select_for_add(BSTree bst,ElemType ele)
{
TNode* temp = bst;
TNode* val;
while(temp)
{
val = temp;
if(ele == temp->data) //存在这个节点
{
cout << "存在这个节点" <<endl;
return NULL;
}
if(ele < temp->data)
{
temp = temp->lchild;
}else{
temp = temp->rchild;
}
}
return val;
}
/**
*二叉搜索树添加节点
*/
Status bst_add(BSTree &bst,ElemType ele)
{
TNode* tnode = (BSTree)malloc(sizeof(TNode));
TNode* temp;
if(!tnode)
{
cout << "分配内存失败" << endl;
}
tnode->data = ele;
tnode->lchild = NULL;
tnode->rchild = NULL;
if(!bst)
{
bst = tnode;
}else{
temp = bst_select_for_add(bst,ele); //查找节点应该插在什么位置
if(!temp)
{
free(tnode); //存在的话,释放tnode
return ERROR;
}else{
if (ele < temp->data) //判断应该插在什么位置
{
temp->lchild = tnode;
}else{
temp->rchild = tnode;
}
}
}
return OK;
}
/**
*二叉搜索树删除节点
*/
Status bst_delete(BSTree &bst,ElemType ele)
{
TNode* tnode = bst;
TNode* parent;
TNode* temp;
if (tnode == NULL) //没有这个节点
{
cout << "not found" << endl;
return ERROR;
}
if (tnode->data == ele) //找到这个节点
{
if (tnode->lchild == NULL && tnode->rchild == NULL) //节点为叶节点
{
bst = NULL;
free(tnode);
}else if (tnode->lchild == NULL) //节点的左孩子为空
{
bst = tnode->rchild;
}else if (tnode->rchild == NULL) //节点的右孩子为空
{
bst = tnode->lchild;
}else{
temp = tnode->rchild;
if (temp->lchild == NULL) //情况A,,节点的右孩子的左孩子为空
{
temp->lchild = tnode->lchild; //情况A的第1步,
}else{
while(temp->lchild) //情况B,,一直找到节点的右孩子下左孩子为空的节点
{
parent = temp;
temp = temp->lchild;
}
parent->lchild = temp->rchild; //情况B的第1步
temp->lchild = tnode->lchild; //情况B的第2步
temp->rchild = tnode->rchild; //情况B的第3步
}
bst = temp; //情况A的第2步,情况B的第4步
free(tnode);
}
}else if (tnode->data > ele)
{
bst_delete(bst->lchild,ele);
}else{
bst_delete(bst->rchild,ele);
}
return OK;
}
/**
*中序排序
*/
void inOrder(BSTree bst)
{
if(!bst)
{
return;
}
inOrder(bst->lchild);
cout << bst->data << " ";
inOrder(bst->rchild);
}
int main(int argc, char const *argv[])
{
BSTree bst;
initBSTree(bst);
bst_add(bst,8);
bst_add(bst,5);
bst_add(bst,10);
bst_add(bst,4);
bst_add(bst,6);
bst_add(bst,9);
bst_add(bst,11);
cout << "插入后形成二叉搜索排序:";
inOrder(bst);
cout << endl;
bst_add(bst,7);
cout << "插入一个7后排序:";
inOrder(bst);
cout << endl;
bst_delete(bst,5);
cout << "删除一个5后排序:";
inOrder(bst);
cout << endl;
return 0;
}
//结果:
//插入后形成二叉搜索排序:4 5 6 8 9 10 11
//插入一个7后排序:4 5 6 7 8 9 10 11
//删除一个5后排序:4 6 7 8 9 10 11