我尝试编码kd树和二叉搜索树。我想知道为什么在插入不平衡数据时bst给我堆栈溢出错误而kd树没有。
二叉搜索树的代码:
void insert(node *&_node, int _val) { //bst insert function, will change raw pointers to smart pointers later
if (_node == NULL) {
_node = new node;
_node->val = _val;
}
else if (_node->val > _val)
insert(_node->left, _val);
else if (_node->val < _val)
insert(_node->right, _val);
}
for (int i = 0; i < 4000;i++) { //inserting unbalanced data, gives me stack overflow error
test.insert(test.root, i);
}
kd-tree的代码:
void insert(Nodeptr &node, int point[], int depth) { //kd tree insert function, Nodeptr is a typedef of unique_ptr<Node>
if (node == NULL) {
node = Nodeptr(new Node(point));
node->axis = depth%dim;
}
else if (node->pt[depth%dim] > point[depth%dim])
insert(node->left, point, depth+1);
else if (node->pt[depth%dim] < point[depth%dim])
insert(node->right, point, depth+1);
}
for (int i = 0; i < 5000; i++) { // inserting unbalanced data, does not give me stack overflow error
point[0] = i;
point[1] = i;
tree.insert(tree.root, point, 0);
}
编辑:visual studio说可能堆大小为224.57kb并且在发生异常时创建了3746个节点,因此它没有真正完成4000次插入