二叉查找树需满足:用二叉查找树统计任意输入的字符串中数字(0-9)出现的次数
对上面建成的二叉查找树进行中序遍历,遍历的结果保存到数组中。
通过二分查找,在上面得到的数组中查询输入的数字在第一步输入的字符串中出现的次数。
#include<iostream>
#include<vector>
using namespace std;
typedef struct BSTNode {
int data; //结点数据域
BSTNode* lchild, * rchild; //左右孩子指针
}BSTNode, * BSTree;
void InsertBST(BSTree& T, int e); //二叉排序树的插入
void CreateBST(BSTree& T); //二叉排序树的创建
void InOrderTraverse(BSTree& T);//中序遍历
vector<int>arry;
int main()
{
BSTree T;
CreateBST(T);//创建二叉树
InOrderTraverse(T);//中序遍历
int temp_i = 0;
cin >> temp_i;
int index = BinarySearch(arry, arry.size(), temp_i);//二分查找
if (index != -1) {
cout << "查找" << arry[index] << "成功";
}
else {
cout << "查找失败";
}
return 0;
}
void InsertBST(BSTree& T, char e) {
//当二叉排序树T中不存在关键字等于e的数据元素时,则插入该元素
if (!T)
{
BSTree S = new BSTNode; //生成新结点
S->data = e; //新结点S的数据域置为e
S->lchild = S->rchild = NULL;//新结点S作为叶子结点
T = S; //把新结点S链接到已找到的插入位置
}
else if (e < T->data)
InsertBST(T->lchild, e);//插入左子树
else if (e > T->data)
InsertBST(T->rchild, e);//插入右子树
}
void CreateBST(BSTree& T) {
//依次读入一个关键字为key的结点,将此结点插入二叉排序树T中
T = NULL;
char ch;
while (cin.get(ch))
{
if(isdigit(ch))
InsertBST(T, ch); //插入二叉排序树T中
}
}
void InOrderTraverse(BSTree& T) {
if (T)
{
InOrderTraverse(T->lchild);
arry.push_back(T->data);
//cout << T->data << "\t";
InOrderTraverse(T->rchild);
}
}
int BinarySearch(vector<int>arr, int len, int target) {
int low = 0;
int high = len;
int mid = 0;
while (low <= high) {
mid = (low + high) / 2;
if (target < arr[mid]) high = mid - 1;
else if (target > arr[mid]) low = mid + 1;
else return mid;
}
return -1;
}
给你个参考吧https://blog.csdn.net/ll1175555/article/details/125248181,前、中、后序遍历都有
如有帮助,望采纳
输入任意字符串(其中包含数字字符)统计数字字符"0–9"分别出现的次数。
//文件名: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;
}