二叉排序樹統計字串
結點的型別:
typedef struct tnode
{
char ch; //字符
int count; //出現次數
struct tnode *lchild,*rchild;
} tnode,*BTree;
完整代碼
//檔案名:exp9-5.cpp
#include<iostream>
using namespace std;
#define MAXWORD 100
typedef struct tnode
// typedef tnode *BTree
{
char ch; //字符
int count; //出現次數
struct tnode *lchild,*rchild;
} tnode ,*BTree;
void CreaTree(BTree &p,char c) //采用遞回方式構造一棵二叉排序樹
{
if (p==NULL) //p為NULL,則建立一個新結點
{
p=new tnode;
p->ch=c;
p->count=1;
p->lchild=p->rchild=NULL;
}
else if (c==p->ch){
p->count++;
}
else if (c<p->ch) {
CreaTree(p->lchild,c);
}
else {
CreaTree(p->rchild,c);
}
}
void InOrder(BTree p) //中序遍歷BST
{
if (p!=NULL)
{
InOrder(p->lchild); //中序遍歷左子樹
cout<<p->ch<<":"<<p->count<<endl;//訪問根結點
InOrder(p->rchild); //中序遍歷右子樹
}
}
int main()
{
BTree root=NULL;
int i=0;
char str[MAXWORD];
cout<<("輸入字串:");
gets(str);
while (str[i]!='\0')
{
CreaTree(root,str[i]);
i++;
}
cout<<"字符及出現次數:\n";
InOrder(root);
cout<<endl;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/115739.html
標籤:其他
上一篇:B-樹
下一篇:選擇排序
