c++11 - 我需要一些可以在现有 BST 实现上实现的实践方法
问题描述
很简单,我必须使用这个预先存在的代码进行课堂测验。我们将不得不实现某种功能。我想知道,我应该使用什么样的功能?我不太擅长现场编码,并且希望尽可能做好准备。
练习版让我们执行名为 Top5() 的函数,它打印出 BST 的最高 5 个元素。所以我完成了这个,我编写了我自己的版本,lowest3(),它返回 BST 中第三低的元素。我只是想知道,还有什么我可以做的,与此类似的困难,我可以改进吗?(简单地说,我不想混淆自己)。
class BTnode {
public:
int key;
BTnode *left, *right, *parent;
BTnode(int key, BTnode *left, BTnode *right, BTnode *parent) :
key(key), left(left), right(right), parent(parent) {};
};
// Desc: A binary search tree (root)
// Inv: All keys in root->left <= root->key <= all keys in root->right
class BST {
private:
// Desc: The root of the BST (NULL if empty)
BTnode *root;
// Desc: Helper function for .insert(key)
BTnode *insertH(BTnode *root, int key);
// this is the data members.
void BST::top5H(BTnode* node, int* count) const{
if(node->right){
top5H(node->right, count);
}
if(*count == 5){
return;
}
cout << node->key << " ";
(*count)++;
if(node->left){
top5H(node->left, count);
}
}
//try to find 5 highest.
void BST::top5() const {
int* count = new int(0);
top5H(root, count);
cout << endl;
free(count);
} // top5
// this is my implementation of top5().
void BST::lowest3H(BTnode* node, int* count, int* arr) const{
if(node->left){
lowest3H(node->left, count, arr);
}
if(*count == 3){
return;
}
cout << node->key << " ";
arr[*count] = node->key;
(*count)++;
if(node->right){
lowest3H(node->right, count, arr);
}
}
//try to find 3rd lowest.
void BST::lowest3() const {
int * arr = NULL;
arr = new int[100];
int* count = new int(0);
int min;
int temp;
lowest3H(root, count, arr);
for(int i = 0; i < 3; i++){
min = i;
for(int j = i+1; j < 100; j++){
if(arr[j] < arr[min]){
min = j;
}
}
temp = min;
arr[min] = arr[i];
arr[i] = arr[temp];
cout << arr[i];
}
cout << endl << arr[2] << endl;
free(count);
}
//This is my implementation of lowest3()
这些工作,对于给我的 BST,假设它们会给我们提供格式良好的示例,所以没有极端情况。
解决方案
推荐阅读
- excel - VBA 代码将主 Outlook 收件箱中的所有未读电子邮件随机拆分到子文件夹中
- javascript - .map() 方法中的参数顺序
- powershell - 使用 Powershell 将 MSMQ 消息从一个队列移动到另一个队列
- java - 在 Java NullPointerException 中为 arrayList 添加每个列表元素
- excel - 基于相似的选项卡名称运行宏
- c# - 当关卡结束时,如何将一个关卡的分数添加到该关卡之外的货币?
- flutter - 如何从 url [Flutter][Dio] 获取文件名
- java - 将具有多列选择的@Query 映射到@Repository 中的Java 对象- 是否可以开箱即用?
- swiftui - 为什么 VStack 不能在带有滚动视图的 GeometryReader 中工作?
- c# - 重定向到 https 部分工作 asp net core