详细知识见《算法导论》第12章
以下使自己写的源代码:
//
动态二分查找树
class
BST
{
public
:
BST(string s, int cnt = 1, BST *l = NULL, BST *r = NULL, BST *pp = NULL)
:str(s), count(cnt), left(l), right(r), p(pp)
{}
public
:
string str; // key
,关键字
int count; //
统计计数,或者是其他的卫星数据
BST *left;
BST *right;
BST *p; //
父节点
};
void
TreeInsert(BST * &root, const string &s);
BST *Delete(BST *root, BST *z);
BST *TreeSearch(BST *root, const string &s);
void
InOrderTreeWalk(BST *x);
BST *TreeMaximum(BST *root);
BST *TreeMinimum(BST *root);
BST *TreeSuccerssor(BST *x);
BST *TreePredecessor(BST *x);
//
插入操作
void
TreeInsert(BST * &root, const string &s) //
注意:使用BST * &
{
BST *y = NULL;
BST *x = root;
while( x != NULL )
{
if( x->str == s )
{
x->count++; return ;
}
else
{
y = x;
if( s < x->str ) x = x->left;
else x = x->right;
}
}
BST *z = new BST(s);
z->p = y;
if( root == NULL ) root = z;
else if( z->str < y->str ) y->left = z;
else y->right = z;
}
//
删除节点
BST *Delete(BST *root, BST *z)
{
BST *x, *y;
if( z->left == NULL || z->right == NULL ) y = z;
else y = TreeSuccerssor(z);
if( y->left ) x = y->left;
else x = y->right;
if( x ) x->p = y->p;
if( y->p == NULL ) root = x;
else if( y == y->p->left ) y->p->left = x;
else y->p->right = x;
if( y != z )
{
z->str = y->str;
z->count = y->count;
}
return y;
}
//
查找
BST *TreeSearch(BST *root, const string &s)
{
BST *x = root;
while( x != NULL && s != x->str )
{
if( s < x->str ) x = x->left;
else x = x->right;
}
return x;
}
//
中序遍历
void
InOrderTreeWalk(BST *x)
{
if( x != NULL )
{
InOrderTreeWalk(x->left);
if( x->count > 1 )
{
cout << x->str << " " << x->count << endl;
}
InOrderTreeWalk(x->right);
}
}
//
最大值
BST *TreeMaximum(BST *root)
{
BST *x = root;
while( x->right != NULL ) x = x->right;
return x;
}
//
最小值
BST *TreeMinimum(BST *root)
{
BST *x = root;
while( x->left != NULL ) x = x->left;
return x;
}
//
后继
BST *TreeSuccerssor(BST *x)
{
if( x->right != NULL ) return TreeMinimum(x->right);
BST *y = x->p;
while( y != NULL && x == y->right )
{
x = y;
y = y->p;
}
return y;
}
//
前趋
BST *TreePredecessor(BST *x)
{
if( x->left != NULL ) return TreeMaximum(x->left);
BST *y = x->p;
while( y != NULL && x == y->left )
{
x = y;
y = y->p;
}
return y;
}
int
main()
{
BST *root = NULL;
...
TreeInsert(root, str);
...
InOrderTreeWalk(root);
...
return 0;
}
题目:JOJ 1490: 487-3279 字符串统计计数
法一:由于其明显的键值关系,使用STL::map.
法二:利用动态的二叉查找树,在插入操作过程中进行统计计数.