1
1、画出对下列存储于数组中的值执行buildheap后得到的最大值堆:
2
10 5 12 3 2 1 8 7 9 4
3
4
先序遍历为12 10 4 1 2 9 5 8 3 7
5
中序遍历为1 4 2 10 5 9 12 3 8 7
6
7
2、假设某字母表各个字母的权如下:
8
Q Z F M T S O E
9
2 3 10 10 10 15 20 30
10
(a)按照这个字母表,一个包含n个字母的字符串采用Huffman编码在最差情
11
况下需要多少位?怎样的串会出现最差情况?
12
13
在最差的情况下需要5*n位,当所有的字母都是Q或者Z的时候。
(b)按照这个字母表,包含n个字母的字符串采用Huffman编码在最佳情况
14
15
下需要多少位?怎样的串会出现最佳情况?
16
在最佳的情况下需要2*n位,当所有的字母都是E或者O的时候。
17
(c)按照一个字母表,一个字母平均需要多少位?
18
(2*30 + 2*20 + 3*15 + 3*10 + 3*10 + 4*10 + 5*3+ 5*2)/100 =2.7
19
∴ 2.7
20
3、编写一个算法来判断两棵树是否相同。
尽可能提高算法效率,并分析算法21
的运行时间代价。
22
template <class Elem>
23
bool Compare(GTNode<Elem>* tree1, GTNode<Elem>* tree2) {
24
GTNode<Elem> *num1, *num2;
25
if (((tree1 == NULL) && (tree2 != NULL)) ||
26
((tree2 == NULL) && (tree1 != NULL)))
27
return 0;
28
if ((t1 == NULL) && (t2 == NULL)) return 1;
29
if (tree1->val() != tree2->val()) return 0;
Num1 = tree1->left_child();
30
31
Num2 = tree2->left_child();
32
while(!((num1 == NULL) && (num2 == NULL))) {
if (!Compare(num1, num2)) return false;
33
34
if (num1 != NULL) num1 = num1->right_value();
35
if (num2 != NULL) num2 = num2->right_value();
36
}}
37
38
O(n)
39
4、编写出一个函数,以一棵树为输入,返回树的结点数目。
要求使用下面给40
出的GenTree和GTNode ADT。
41
// General tree node ADT
42
Template <class Elem> class GTNode {
43
Public:
44
GTNode (const Elem&); // Constructor
45
~GTNode ( ); // Destructor
46
Elem value ( );
47
Bool isLeaf ( );
48
GTNode * parent ( );
GTNode * right_sibling ( );
49
50
Void setValue ( Elem &);
51
Void insert_first(GTNode <Elem>* n); // Insert first child
Void insert_next(GTNode <Elem> * n); // Insert next sibling
52
53
Void remove_first ( ); // Remove first child
54
Void remove_next ( ); // Remove right sibling
55
};
56
//General tree ADT
57
Template <class Elem> class GenTree {
58
Private:
59
Void printhelp ( GTNode *) ; // Print helper function 60
Public :
61
GenTree ( ); //Constructor
62
~GenTree ( ); //Destructor
63
Void clear ( ); // Send nodes to free store
64
GTNode* root ( ); // Retrun the root
65
// Combine two subtrees
66
Void newroot (Elem& , GTNode <Elem>* ,GTNode<Elem>* );
67
Void print ( ); // print a tree
};
68
69
70
template <class Elem>
71
int gencount(GTNode<Elem>* subroot) {
72
if (subroot == NULL) return 0
73
int count = 1;
74
GTNode<Elem>* temp = rt->leftmost_child();
75
while (temp != NULL) {
76
count += gencount(temp);
77
temp = temp->right_sibling();
78
}
79
return count;
80
}
81
82
5、对下列用(6.3)式编码方法写出的树的顺序表示,画出树的形状。
83
XPC)Q)RV)M))))
84。