繁体   English   中英

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

[英]Update AVL tree code to perform find OR insert

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

我从以下网址获得了AVL树实现的基本代码: http//www.geeksforgeeks.org/avl-tree-set-2-deletion/

我正在尝试制作一个新函数,如果该键不在树中,则将插入一个新节点,否则,如果它在树中,请给我访问该节点的权限,以便我查看它。 我是一名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);

您可以仅依靠他人编写的代码。

一种这样的实现是AVL树Boost实现 ,您可以通过CRAN包BH轻松访问它,从而为您提供在R(和C ++)中使用的Boost Headers。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM