二叉查找树(Binary Search Tree),又称二叉搜索树,二叉排序树。
性质:
- 若它的左子树不为空,则左子树上所有节点的值均小于它的根节点的值;若它的右子树不为空,则右子树上所有节点的值均大于它的根节点的值;它的左右子树也分别为二叉排序树。
操作:
- 插入一个数值
- 查询是否包涵某个数值
- 删除某个数值
#include<bits/stdc++.h>
using namespace std;
struct node
{
int val;
node *l, *r, *pa;
};
node * root = NULL;
void ins(int x) // 插入节点
{
if(root==NULL){ // 如果当前根节点为空,则待插入节点为根节点
node *p = new node;
p->val = x; // 节点值
p->l = NULL; // 左节点
p->r = NULL; // 右节点
root = p;
}else{
node * a = new node; // 搜索树上的节点(最终为待插入节点的位置)
node * b = new node; // 待插入节点的父节点
node * c = new node; // 待插入节点
a = root; // 从根节点开始搜索
b = NULL; // 初始NULL
c->val = x; // 待插入节点
c->l = NULL;
c->r = NULL;
while(a!=NULL){ // 搜索到叶节点为止
b = a; // b为a的父节点
if(x<a->val){ // 搜索左子树
a = a->l;
}else if(x>a->val){ // 搜索右子树
a = a->r;
}
}
c->pa = b; // 赋值待插入节点的父节点
// 判断待插入节点值与其父节点值的关系(从而判断插入左节点还是右节点)
if(x<b->val){
b->l = c;
}else{
b->r = c;
}
}
}
node * ffind(node *t, int x) // 查找节点
{
while(t!=NULL&&t->val!=x) // 当前节点非空,并且节点值不等于待查询值
{
if(x>t->val){ // 搜索右子树
t = t->r;
}else if(x<t->val){ // 搜索左子树
t = t->l;
}
}
return t; // 返回节点
}
node * ffindmax(node *t) // 查找以t节点为根的子树的节点值最大的节点
{
while(t->r!=NULL) // 搜索右子树
{
t = t->r;
}
return t; // 返回节点
}
node * ffindmin(node *t) // 查找以t节点为根的子树的节点值最小的节点
{
while(t->l!=NULL) // 搜索左子树
{
t = t->l;
}
return t; // 返回节点
}
void del(node *t) // 删除节点
{
/*
* 如果待删除的节点至少有一个子节点为空,直接删除该节点即可
* 如果待删除节点有两个子节点,则用其右子树中值最小的节点代替待删除节点,并删除其右子树中值最小的节点
*/
node * y = new node; // 待删除节点p
if(t->l==NULL||t->r==NULL){ // 待删除节点至少有一个子节点为空
y = t;
}else{
y = ffindmin(t->r);; // 待删除节点有两个子节点,则用待删除的节点的右子树的最小值节点代替
}
node * x = new node; // p的子节点
if(y->l!=NULL){
x = y->l; // x为p的左节点
}else{
x = y->r; // x为p的右节点
}
if(x!=NULL) x->pa = y->pa; // 如果子节点非空,更改子节点父节点为子节点的父节点的父节点
if(y->pa==NULL){ // 如果待删除点为根节点,直接将x赋值给根节点
root = x;
}else if(y==y->pa->l){ // y节点是其父节点的左节点
y->pa->l = x;
}else{ // y节点是其父节点的右节点
y->pa->r = x;
}
if(y!=t) t->val = y->val; // 删除的节点不是该节点本身,更新父节点
}
void pre(node *x) // 前序遍历(根-左-右)
{
if(x!=NULL){
printf("%d ", x->val);
pre(x->l);
pre(x->r);
}
}
void ino(node *x) // 中序遍历(左-右-根)
{
if(x!=NULL){
ino(x->l);
printf("%d ", x->val);
ino(x->r);
}
}
void pos(node *x) // 后序遍历(左-右-根)
{
if(x!=NULL){
pos(x->l);
pos(x->r);
printf("%d ", x->val);
}
}
void ruin(node *t) // 销毁树
{
if(t){
ruin(t->l);
ruin(t->r);
free(t);
}
}
int main()
{
// 建树
int n;
cin >> n;
int x;
for(int i = 0; i < n; i++)
{
cin >> x;
ins(x);
}
// 遍历
cout << "preorder:";
pre(root);
cout << endl;
cout << "inorder:";
ino(root);
cout << endl;
cout << "posorder:";
pos(root);
cout << endl;
// 查询
int q;
cin >> q;
while(q--)
{
cin >> x;
cout << ffind(root,x) << endl;
}
// 删除
cin >> q;
while(q--)
{
cin >> x;
node * p = new node;
p = ffind(root,x); // 搜索待删除节点的位置
del(p);
cout << "preorder:";
pre(root);
cout << endl;
cout << "inorder:";
ino(root);
cout << endl;
cout << "posorder:";
pos(root);
cout << endl;
}
// 销毁
ruin(root);
return 0;
}