[英]Binary search tree insertion data problem
i'm trying to implement my own binary search tree, i've stucked on inserting data, can you explain me what i'm doing wrong . 我正在尝试实现自己的二进制搜索树,我一直坚持插入数据,您能解释一下我在做什么错。
void tree::add(int data) {
tree * tmp = new tree;
if (root == NULL) {
root = tmp;
root->data = data;
root->left = NULL;
root->right = NULL;
}
else if (data <= root->data) {
left = tmp;
left->data = data;
left->left = NULL;
left->right = NULL;
while (tmp != NULL) {
if (data <= left->data) {
tmp = left->left;
} else {
tmp = left->right;
}
}
}
I'm trying to fill left node, if data i smaller than root but if data is greater than this leaf but still smaller than root it should be right child, but actually i have access volation 我正在尝试填充左节点,如果数据i小于根,但如果数据大于此叶但仍小于根,则它应该是正确的子级,但实际上我具有访问权限
You should revise the logic of your algorithm: 您应该修改算法的逻辑:
//here you set the pointers to null
left->left = NULL;
left->right = NULL;
while (tmp != NULL) {
if (data <= left->data) {
// here at the first time
tmp = left->left;
} else {
// or here
tmp = left->right;
}
// tmp will be set to null and the exection will end immediately
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.