POJ-2418 Hardwood Species(二叉搜索树)

思路就是先将每个单词存进二叉树中,没出现一次,修改该单词所在结点的cnt++;

最后通过递归中序遍历输出结果。

思路很清晰,主要注意一下指针的使用,想一想为什么要这么用?

简单的解释就是,insert函数修改的是指针的属性而不是指针指向的目标地址内容的属性。

代码:

#include<iostream> 
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
int sum=0;
//结构体里面似乎不能用string
// 指针的使用 
struct node{
    int cnt;
    char word[31];
    node*l;
    node*r;
};


void insertBST(node**root,char* word){
    if(*root==NULL){
        node*p=(node*)malloc(sizeof(node));
        p->l=NULL;p->r=NULL;
        p->cnt=1;
        strcpy(p->word,word);
        *root=p;
    }
    else{
        //if(word==(*root)->word){
        if(strcmp(word,(*root)->word)==0){
            ((*root)->cnt)++;
        }
        else if(strcmp(word,(*root)->word)<0){
            insertBST(&((*root)->l),word);
        }
        else{
            insertBST(&((*root)->r),word);
        }
    }
}

void midsearch(node*root){
    if(root!=NULL){
        midsearch(root->l);
        printf("%s %.4lf\n",root->word,((double)root->cnt/(double)sum)*100);
        midsearch(root->r);
    }
}

int main(void){
    node* root;
    char w[31];
    while(gets(w)!=NULL){
        insertBST(&root,w);//指针的指针,所以取的是root的地址而不是root 
        sum++;
    }
    midsearch(root);
    return 0;
}

 

posted @ 2018-04-07 17:21  KYSpring  阅读(275)  评论(0编辑  收藏  举报