zoukankan      html  css  js  c++  java
  • 二叉排序树统计字符串中出现的字符及其次数

    二叉排序树统计字符串

    结点的类型:

                  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]!='') 
    	{
    		CreaTree(root,str[i]);
    		i++;
    	}
    	cout<<"字符及出现次数:
    ";
    	InOrder(root);
        cout<<endl;
    	return 0;
    }
    
    
    
    ♪(^∇^*)♪(^∇^*)(~ ̄▽ ̄)~有没有感觉很棒呀!!!(#^.^#),(*^▽^*)O(∩_∩)O哈哈~
  • 相关阅读:
    结构和联合
    字符串、字符和字节
    数组
    函数
    指针
    操作符和表达式
    语句
    数据
    TinyXML2 使用
    是否忘记了向源中添加“#include "StdAfx.h"”?
  • 原文地址:https://www.cnblogs.com/ygjzs/p/12063134.html
Copyright © 2011-2022 走看看