PTA-7-24 树种统计(二叉搜索树的基本操作)

题目:https://pintia.cn/problem-sets/15/problems/839

输入数字n,代表有颗树,输入n个树的名称(含空格),按字典的顺序输出每种树名称及其所占比例。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef char type;
#define MAX 33

typedef struct Tree{
    struct Tree *left,*right;
    type data[MAX];
    int count;
}Tree,*PTree;

PTree Insert(PTree pt,char tmp[]){
    if(!pt){
        pt=(PTree)malloc(sizeof(Tree));
        strcpy(pt->data,tmp);
        pt->left=pt->right=NULL;
        pt->count=1;
    }
    else{
        int x=strcmp(pt->data,tmp);
        if(x<0)         pt->right=Insert(pt->right,tmp);
        else if(x>0)    pt->left=Insert(pt->left,tmp);
        else            pt->count++;
    }
    return pt;
}

void Show(PTree pt,int n){
        if(pt){
            Show(pt->left,n);
            printf("%s ",pt->data);
            printf("%.4lf%%\n",(double)pt->count/n*100);
            Show(pt->right,n);
        }
}

int main(){
    int n;
    scanf("%d",&n);
    getchar();
    PTree pt=NULL;
    for(int i=0;i<n;i++){
        char ch[MAX];
        gets(ch);
        pt=Insert(pt,ch);
    }
    Show(pt,n);
}

拓展:二叉搜索树的找最大值和删除结点

PTree FindMax(PTree &pt){
    if(pt){
        while(pt->right)
            pt=pt->right;
    }
    return pt;
}

PTree Delete(PTree pt,char tmp[]){
    if(!pt)     printf("No Found\n");
    else{
        int x=strcmp(pt->data,tmp);
        if(x<0)         pt->right=Delete(pt->right,tmp);
        else if(x>0)    pt->left=Delete(pt->left,tmp);
        else{                           //所删除结点含左右子树
            if(pt->left&&pt->right){
                PTree tem=FindMax(pt->left);    //从结点的左子树找最大值来顶替结点
                strcpy(pt->data,tem->data);
                pt->left=Delete(pt->left,tem->data);
            }else{                  //所删除结点只含左子树或右子树
                    PTree tem=pt;
                    if(pt->left)    pt=pt->left;
                    else           pt=pt->right;
                free(tem);
            }
        }
    }
    return pt;
}

猜你喜欢

转载自blog.csdn.net/qq_39681830/article/details/81273564