目录
1.利用一棵二叉排序树统计字符串中出现的字符及其次数。
结点的类型:
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
{
char ch; //字符
int count; //出现次数
struct tnode *lchild,*rchild;
} tnode ,*BTree;
void CreatTree(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){
CreatTree(p->lchild,c);
}
else
CreatTree(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')
{
CreatTree(root,str[i]);
i++;
}
cout<<"字符及出现次数:\n";
InOrder(root);
cout<<endl;
return 0;
}
2.设计算法判断一棵二叉树是否为二叉排序树。
提示:(1)根据二叉排序树的性质,在进行中序遍历的时候,当前结点的值总是大于前驱结点的值 , 需要在遍历时保存前驱结点的值。
(2)也可根据二叉排序树的定义递归实现。
指路这篇代码实现2