gpt4 book ai didi

c++ - 如何将我的函数更改为构造函数?

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:06 25 4
gpt4 key购买 nike

我需要制作一个参数化的构造函数,在给定排序数组的情况下创建一个完美平衡的二叉搜索树。我知道如何创建一个创建 BST 的函数,但如何从构造函数创建 BST?这是我的功能:

    node * sortedArrayBST(double * arr, int start, int end)
{
int mid = (start + end)/2;
if (start > end)
{
return NULL;
}
//because the array will be sorted
//the root of the tree will contain the item in the middle of the array so everything less than the middle will go in the left subtree
//and everything greater than the middle will go in the right subtree

node * root = new node(arr[mid]);
//recursively make left subtree
root->left = sortedArrayBST(arr, start, end-1);
//recursively make left subtree
root->right = sortedArrayBST(arr, mid + 1, end);

return root;
}

最佳答案

class BST
{
public:
BST (double * arr, int start, int end)
{
int mid = (start + end)/2;
if (start > end)
{
std::cerr << "Invalid BST tree."
}
//because the array will be sorted
//the root of the tree will contain the item in the middle of the array so everything less than the middle will go in the left subtree
//and everything greater than the middle will go in the right subtree

root = new node(arr[mid]);
node *temp, *parent;
for (num = arr[mid/2]; start <= end;)
if (num <= arr[end]){
parent = temp;
temp=temp->left;
end = (start + end)/2;
} else {
parent = temp;
temp=temp->right;
start = (start + end)/2;
}
}
//recursively make left subtree
root->right = sortedArrayBST(arr, mid + 1, end);
}
private :
node * root;
}

关于c++ - 如何将我的函数更改为构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49888987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com