我需要创建一个参数化构造函数,在给定排序数组的情况下创建一个完美平衡的二叉搜索树。我知道如何创建一个创建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;
}
答案 0 :(得分:0)
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;
}