更新AVL树代码以执行查找或插入

时间:2014-04-09 15:52:16

标签: c++ c r segmentation-fault avl-tree

我想在特定算法中使用AVL树。我正在制作一个R包,所以我想坚持使用C或C ++实现(目前使用C实现)。

我从http://www.geeksforgeeks.org/avl-tree-set-2-deletion/

获得了AVL树实现的基本代码

我正在尝试创建一个新函数,如果键不在树中,将插入一个新节点,否则如果它在树中,请让我访问该节点,以便我可以查看它。我是一个noobie C程序员,但我遇到了几个障碍。

这是我目前的实施。在主函数中,我插入几个键并打印预订,以检查插入是否正常工作(它们确实如此)。然后我尝试插入已经在树中的键。这导致了一个段错误:(任何人都可以帮助我吗?这可能只是我的C的一个简单问题:

struct node* specialInsert(struct node* root, struct node* result, int *numBefore, int key, bool *flag){
    //We are inserting a new (non-root) node!
    if (root == NULL){
        struct node* res = newNode(key);
        res->equalCount = key;
        *numBefore = 0;
        *flag = true;
        return(res);
    }else if( key == root->key){
        *flag = false;
        *numBefore = root->leftCount;
        root->equalCount = root->equalCount + key;

        if(result == NULL){
            struct node* result = newNode(root->key);
        }

        //printf("result key is: %d\n", result->key);

        return root;
    }else if( key < root->key){
        root->left = specialInsert(root->left, result, numBefore, key, flag);
        root->leftCount = root->leftCount + key;
        //if(*flag) update(root, key);
        //else return(root->left);
        update(root,key);
    } else if( key > root->key){
        root->right = specialInsert(root->right, result, numBefore, key, flag);
        *numBefore = *numBefore + root->leftCount + root->equalCount;
        root->rightCount = root->rightCount + key;
        //if(*flag) update(root, key);
        //else return(root->right);
        update(root,key);
    }
}
struct node* findOrInsert(struct node* root, struct node* result, int *numBefore, int key){
    bool *flag;
    bool val = false;
    flag = &val;

    /* 1.  Perform the normal BST rotation */
    if (root == NULL){
        struct node* res = newNode(key);
        *numBefore = 0;
        res->equalCount = key;
        return(res);
    }
    else return( specialInsert(root, result, numBefore, key, flag) );


}

在我的主要功能中:

struct node *root2 = NULL;
struct node *result = NULL;

root2 = findOrInsert(root2, result, x, 9);
root2 = findOrInsert(root2, result, x, 5);
root2 = findOrInsert(root2, result, x, 10);
root2 = findOrInsert(root2, result, x, 0);
root2 = findOrInsert(root2, result, x, 6);
root2 = findOrInsert(root2, result, x, 11);
root2 = findOrInsert(root2, result, x, -1);
root2 = findOrInsert(root2, result, x, 1);
root2 = findOrInsert(root2, result, x, 2);


preOrder(root2);
printf("\n");

root2 = findOrInsert(root2, result, x, 9);
printf("Number of elements less than %d: %d\n", result->key,result->leftCount);

1 个答案:

答案 0 :(得分:1)

您可以简单地依赖其他人编写的代码。

一个这样的实现是Boost implementation of AVL Trees,您可以通过CRAN package BH轻松访问它,它为您提供了在R(和C ++)中使用的Boost Headers。

当然,您也可能喜欢调试自己的数据结构,这也是有用的。在这种情况下,gdb可能会有用......