【发布时间】:2018-04-17 23:36:15
【问题描述】:
我需要创建一个参数化的构造函数,在给定排序数组的情况下创建一个完美平衡的二叉搜索树。我知道如何创建一个创建 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;
}
【问题讨论】:
-
构造函数没有返回类型,你要如何返回节点*?
-
当新手寻求帮助时,我希望每次看到投反对票时都能得到一分钱......
-
构造函数必须是结构/类的成员。你需要一个结构或一个类。
-
学究气(但我们不都是这样)。
int mid = (start + end)/2;有一个潜在的问题,如果值足够大,它可能会溢出 int。欲了解更多信息,请参阅here。您不太可能使用那么大但理论上仍然可行的数组。 -
提示您的努力:在stackoverflow.com/a/45514477/2785528 上查看我的回答。请注意,我有两个协作类:BTree_t 和 Node_t。分离这些问题允许 BTree_t 包含“Node_t* m_root”,即保存一棵树的根的地方。 Btree 方法检查各种树问题(满或空等),但通常调用 m_root->methodX();其中各种方法是节点插入的细节,showTallView, searchR [Recursive], showBR [BreadthFirst, or wide view Recursive], showDFioR [depth first, in-order, Recursive]等(我喜欢递归!)跨度>
标签: c++ function constructor binary-search-tree