poj2418 (二叉搜尋樹)

來源:互聯網
上載者:User

        其實這題方法應該還是挺多樣的,trie啦,hash啦等等,bst寫的少,因此就練了練手。

#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct tNode{char species_name[31];struct tNode* left;struct tNode* right;int count;}Node;Node* root=NULL;char str[31];int total_count=0;Node* create_node(char* str,Node* parent,int left){Node* node=(Node*)malloc(sizeof(Node));strcpy(node->species_name,str);node->left=NULL;node->right=NULL;node->count=1;if(parent){if(left){parent->left=node;}else{parent->right=node;}}return node;}/***search,如果search不到,insert*/void search_insert(Node* node){int result=strcmp(str,node->species_name);if(result==0){node->count++;}if(result>0){if(node->right){search_insert(node->right);}else{create_node(str,node,0);}}if(result<0){if(node->left){search_insert(node->left);}else{create_node(str,node,1);}}}void inorder(Node* node){//按順序輸出結果嘛,當然是中序if(!node){return;}inorder(node->left);printf("%s %.4f\n",node->species_name,100.0*node->count/total_count);inorder(node->right);free(node);}int main(void){while(gets(str)!=NULL){if(root){search_insert(root);}else{root=create_node(str,NULL,0);}total_count++;}inorder(root);return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.