Part I.Introduction
温馨提示:本文是BBST的基础,请在学习BBST之前阅读。
BST是一棵二叉树。
从微观上来讲,BST的每个节点都大于其左节点,且小于其右节点。
从宏观上来将,BST的每个节点都大于其左子树的每个节点,且小于其右子树的每个节点。
以上性质称为BST的顺序性。
通过一些例子和分析我们不难发现,一棵BST的中序遍历是有序的。这个性质我们称为BST的单调性。
如图即为一棵BST。
由于这是一棵二叉树,我们可以通过递归定义法来定义这棵树。
struct node{
int key,val,l,r;
}tree[maxn];
Part II.Find
由BST的顺序性,每走到一个节点,我们只需将目标值与当前节点的key值比较后决定往左/右走,直至走到目标值所在的节点。
int find(int rt,int y){
if (!rt) return -1;
if (y==tree[rt].key) return rt;
if (y<tree[rt].key) return find(tree[rt].l,y);
if (y>tree[rt].key) return find(tree[rt].r,y);
}
Part III.Insert
与Find操作类似,每走到一个节点,如果目标值与当前节点的Key值相同,那么将Val++后return即可;否则往左右的其中之一走。如果走到空节点,则新建节点。
void insert(int &rt,int y){
if (!rt){
rt=++tot;
tree[rt].key=y;
tree[rt].val=1;
tree[rt].l=tree[rt].r=0;
return;
}
if (y==tree[rt].key){
tree[rt].val++;
return;
}
if (y<tree[rt].key){
insert(tree[rt].l,y);
return;
}
if (y>tree[rt].key){
insert(tree[rt].r,y);
return;
}
}
Part IV.Delete
温馨提示:由于今后普通BST基本都会用BBST代替,所以Delete操作可用今后BBST的Delete操作代替。此章请选择性阅读。
Delete操作是BST的难点之一。
我们分3种情况讨论(设该节点为P):
Case 1.若P为叶节点,删除该点不会破坏整棵树的形态,那么直接删除即可。
Case 2.若P只有左儿子或只有右儿子,那么直接将其左/右儿子提上来即可,这时也不会破坏整棵树的形态。
Case 3.若P的左右儿子均非空。在此介绍一种方法:将P节点右子树的最小节点与P节点交换。由于交换后的P不会有左儿子,那么就回到了Case 1或Case 2,将其删除即可。
void del(int y){
int u=find(root,y);
if (!u) return;
if (tree[u].val>1){tree[u].val--;return;}
if (!tree[u].l || !tree[u].r){if (!tree[u].l) u=tree[u].r;else u=tree[u].l;return;}
int v=minode(tree[u].r);
swap(tree[u],tree[v]);
if (!tree[v].l) v=tree[v].r;else v=tree[v].l;
}
Part V.Code
/*
* Algorithm:BST
* Author:PYC
*/
#include <cstdio>
#include <algorithm>
#define maxn 1000000
using namespace std;
int m,root,tot;
struct node{int key,val,l,r;}tree[maxn];
int count(int &root,int y){
if (!root) return 0;
if (y==tree[root].key) return tree[root].val;
if (y<tree[root].key) return count(tree[root].l,y);
if (y>tree[root].key) return count(tree[root].r,y);
}
int find(int &root,int y){
if (!root) return 0;
if (y==tree[root].key) return root;
if (y<tree[root].key) return find(tree[root].l,y);
if (y>tree[root].key) return find(tree[root].r,y);
}
void insert(int &root,int y){
if (!root){tree[root=++tot].key=y;tree[root].val=1;return;}
if (y==tree[root].key){tree[root].val++;return;}
if (y<tree[root].key) insert(tree[root].l,y);
if (y>tree[root].key) insert(tree[root].r,y);
}
int minode(int &root){if (!tree[root].l) return root;else minode(tree[root].l);}
void del(int y){
int u=find(root,y);
if (!u) return;
if (tree[u].val>1){tree[u].val--;return;}
if (!tree[u].l || !tree[u].r){if (!tree[u].l) u=tree[u].r;else u=tree[u].l;return;}
int v=minode(tree[u].r);
swap(tree[u],tree[v]);
if (!tree[v].l) v=tree[v].r;else v=tree[v].l;
}
int main(){
scanf("%d",&m);
for (int i=1;i<=m;++i){
int x,y;
scanf("%d%d",&x,&y);
if (x==1) printf("%d\n",count(root,y));
if (x==2) insert(root,y);
if (x==3) del(y);
}
return 0;
}
Part VI.Thank You!
Thank you for reading!
By Charlie Pan
Mar 4,2014