阅读: 15 评论: 0 作者: over 发表于 2009-10-18 12:21 原文链接
题目大意:对给定的一些树名进行字典排序并输出所占的比例。
思路不难就是对给定的数进行字典排序,可是如何存储和如何进行排序是解决问题的关键了,这里我们用到一种叫做二叉搜索树的数据结构。
树的节点结构:
1 struct BiNode
2 {
3 char Name[50];
4 BiNode *lchild,*rchild;
5 int count;
6 };
插入节点的伪代码:
1 judge = strcmp(Name, root->Name);
2 if(judge == 0) 此节点的count++;
3 else if(judge > 0)
4 if(左子树存在) 递归遍历左子树
5 else 添加一个左子树节点
6 else if(judge < 0)
7 if(右子树存在) 递归遍历右子树
8 else 添加一个右子树节点
建树的过程其实就是一个调用插入函数。
进行一次中序遍历节点输出Name域和所占比例及可。
代码如下:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
1
2 #include <iostream>
3 #include <string>
4 using namespace std;
5 struct BiNode
6 {
7 char Name[50];
8 BiNode *lchild,*rchild;
9 int count;
10 };
11 class BiSortTree
12 {
13 public:
14 BiSortTree(){};
15 void Creat();
16 ~BiSortTree(){}
17 void inOrderPrint(BiNode *root);
18 void InsertBST(BiNode *root, char *s);
19 BiNode *SearchBST(BiNode *root, char *name);
20 BiNode *GetRoot(){return root;}
21 private:
22 BiNode *root;
23 int sum;
24 };
25 void BiSortTree::inOrderPrint(BiNode *root)
26 {
27 double person;
28 if(root->lchild) inOrderPrint(root->lchild);
29 cout<<root->Name<<" ";
30 person = (double)(root->count)/(double)(sum);
31 person *= 100;
32 printf("%.4lf\n",person);
33 if(root->rchild) inOrderPrint(root->rchild);
34 }
35 void BiSortTree::Creat()
36 {
37 char Name[50];
38 sum=1;
39 gets(Name);
40 root = new BiNode;
41 strcpy(root->Name, Name);
42 root->count = 1;
43 root->lchild = NULL;
44 root->rchild = NULL;
45 while(gets(Name))
46 {
47 if(Name[0] == '\0') break;
48 InsertBST(root,Name);
49 sum++;
50 }
51 }
52 void BiSortTree::InsertBST(BiNode *root,char *s)
53 {
54 int judge = strcmp(s,root->Name);
55 if(judge == 0) root->count++;
56 else if(judge < 0)
57 {
58 if(root->lchild) InsertBST(root->lchild, s);
59 else
60 {
61 root->lchild = new BiNode;
62 root->lchild->lchild = root->lchild->rchild = NULL;
63 root->lchild->count = 1;
64 strcpy(root->lchild->Name, s);
65 }
66 }
67 else
68 {
69 if(root->rchild) InsertBST(root->rchild, s);
70 else
71 {
72 root->rchild = new BiNode;
73 root->rchild->lchild = root->rchild->rchild = NULL;
74 root->rchild->count = 1;
75 strcpy(root->rchild->Name, s);
76 }
77 }
78 }
79 int main()
80 {
81 BiSortTree BiTree;
82 BiTree.Creat();
83 BiTree.inOrderPrint(BiTree.GetRoot());
84 return 0;
85 }
86
![](https://www.cnblogs.com/terminatro/aggbug/1585427.html?type=1)
发表评论
新闻频道:苹果平板机实物图片现身?
推荐链接:Windows 7专题发布
网站导航:博客园首页 个人主页 新闻 社区 博问 闪存 知识库