二进制搜索树插入数据问题

问题描述 投票:1回答:1

我正在尝试实现自己的二叉搜索树,我一直坚持插入数据,你能解释一下我做错了什么。

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小于root但是如果数据大于此叶但仍小于root它应该是正确的子节点,但实际上我有访问声音

c++ binary-search-tree
1个回答
0
投票

您应该修改算法的逻辑:

//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
}
© www.soinside.com 2019 - 2024. All rights reserved.