1. 程式人生 > >SDUT3375資料結構實驗之查詢三:樹的種類統計

SDUT3375資料結構實驗之查詢三:樹的種類統計

剛AC的新鮮程式碼,馬上給安排過來
用的還是***二叉排序樹***的知識,只不過比較的物件由數字變成了字串,而每個節點有多加了一個記錄物件也就是每一種樹的數量data

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

typedef struct note{
    char s[55];
    int data;//樹的數量
    struct note *l,*r;
}tree;

void creat(tree *&root,
char *s){ if(root==NULL){//當為NULL時,建立新tree root = new tree; strcpy(root->s,s);//字串的copy函式 root->data = 1;//此時此種樹的數量為1 root->l = NULL; root->r = NULL; return ; } else{ if(strcmp(s,root->s)<0)//三種比較,如果相等的話,當前樹的種類++ creat
(root->l,s); else if(strcmp(s,root->s)==0) root->data++; else creat(root->r,s); } } void zhongxu(tree *root,int n){//按照字典序輸出,用到中序遍歷 if(root){ zhongxu(root->l,n);//首先左 double x = 100.0*root->data/n;//首先算出比例,然後輸出當前的樹的名字,然後按格式輸出即可 cout<<
root->s<<" "; printf("%.2lf",x); printf("%c\n",'%'); zhongxu(root->r,n);//莫忘右 } } int main() { int n; tree *root = NULL; cin>>n; getchar(); for(int j=0; j<n; j++){ char s[1010]; gets(s); int len = strlen(s); for(int i=0; i<len; i++){ if(s[i]<=90 && s[i]>=65){//如果是大寫程式設計小寫,也可用函式tolower s[i]=s[i]+32; } } creat(root,s); } zhongxu(root,n); return 0; }