C++ 二叉搜索树插入数据问题

C++ 二叉搜索树插入数据问题,c++,binary-search-tree,C++,Binary Search Tree,我正在尝试实现我自己的二叉搜索树,我在插入数据方面遇到了困难,你能解释一下我做错了什么吗 void tree::add(int data) { tree * tmp = new tree; if (root == NULL) { root = tmp; root->data = data; root->left = NULL; root->right = NULL; } else

我正在尝试实现我自己的二叉搜索树,我在插入数据方面遇到了困难,你能解释一下我做错了什么吗

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;
            }

        }
}

void树::添加(int数据){
tree*tmp=新树;
if(root==NULL){
根=tmp;
根->数据=数据;
根->左=空;
root->right=NULL;
}
else if(数据){
左=tmp;
左->数据=数据;
左->左=空;
左->右=空;
while(tmp!=NULL){
if(数据){
tmp=左->左;
}否则{
tmp=左->右;
}
}
}

我试图填充左节点,如果数据I小于根,但如果数据大于此叶,但仍然小于根,则应该是右子节点,但实际上我有访问权限,您应该修改算法的逻辑:

//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
}
//这里您将指针设置为null
左->左=空;
左->右=空;
while(tmp!=NULL){
if(数据){
//第一次在这里
tmp=左->左;
}否则{
//还是在这里
tmp=左->右;
}
//tmp将设置为null,执行将立即结束
}

您应该修改算法的逻辑:

//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
}
//这里您将指针设置为null
左->左=空;
左->右=空;
while(tmp!=NULL){
if(数据){
//第一次在这里
tmp=左->左;
}否则{
//还是在这里
tmp=左->右;
}
//tmp将设置为null,执行将立即结束
}

调试器向您展示了什么?它应该带您到错误发生的那一行,让您检查所有变量。“您能解释一下我做错了什么吗?”不使用纸和笔我会说。做一些奇怪的绘图!你的调试器向你展示了什么?它应该把你带到错误发生的地方,让你检查所有的变量。“你能解释一下我做错了什么吗?”不使用纸和笔我会说。做一些奇怪的绘图!