[c++]代码库
#include <iostream>
using namespace std;
typedef int KeyType;
struct ElemType{KeyType key;int count;};
typedef struct BiTNode
{
ElemType data;
BiTNode *lc,*rc;
}*BiTree;
void BiTreeLists(BiTree T, void visit(ElemType));
BiTree CreatNode(ElemType x);
bool InsertBST(BiTree &T, ElemType x) ;
void visit(ElemType data);
void CreatBST(BiTree &T, int n, ElemType a[]);
void countall(BiTree &T);
int main()
{
BiTree T; int n = 12,i;
KeyType a[] = { 1,1,2,5,3,5,5,4,4,7,7,8 };
ElemType b[12];
for ( i = 0; i < n; i++) b[i].key =a[i];
CreatBST(T, n,b);
cout << "元素序列:" << endl;
for ( i = 0; i < n; i++)
{
cout<<a[i] << " ";
}
cout << endl;
countall(T);
return 0;
}
BiTree CreatNode(ElemType x)
{
BiTree p;
p = new BiTNode; p->data = x;p->data.count = 1;
p->lc = p->rc = NULL;
return p;
}
void BiTreeLists(BiTree T, void visit(ElemType))
{
if (!T) { cout << "#"; return; }
visit(T->data);
if (T->lc || T->rc) {
cout << "(";
BiTreeLists(T->lc, visit);
cout << ",";
BiTreeLists(T->rc, visit);
cout << ")";
}
}
void CreatBST(BiTree &T, int n, ElemType a[])
{
T = NULL;
for (int i = 0; i < n; i++) {
InsertBST(T, a[i]);
}
}
void visit(ElemType data)
{
cout << data.key;
}
bool InsertBST(BiTree &T, ElemType x)
{
if (!T)
{
T = CreatNode(x); return true;
}
else if (T->data.key == x.key)
{
T->data.count++;
return false;
}
else if (x.key < T->data.key)
{
return InsertBST(T->lc, x);
}
else
{
return InsertBST(T->rc, x);
}
}
void countall(BiTree &T)
{
if (!T)return;
countall(T->rc);
cout << "元素" << T->data.key << "出现的次数:" << T->data.count << endl;
countall(T->lc);
}