首页 > 解决方案 > 我需要一些可以在现有 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,假设它们会给我们提供格式良好的示例,所以没有极端情况。

标签: c++11recursionbinary-search-tree

解决方案


推荐阅读