Я хотел бы использовать деревья AVL в конкретном алгоритме. Я делаю пакет R, поэтому хочу придерживаться реализаций C или C++ (в настоящее время использую реализацию C).
Я получил базовый код для реализации дерева AVL с: http://www.geeksforgeeks.org/avl-tree-set-2-deletion/
Я пытаюсь создать новую функцию, которая будет вставлять новый узел, если ключа нет в дереве, в противном случае, если он есть в дереве, дайте мне доступ к узлу, чтобы я мог его посмотреть. Я новичок в программировании на C, поэтому я сталкиваюсь с несколькими проблемами.
Вот моя текущая реализация. В основную функцию вставляю несколько ключей и распечатываю предзаказ, чтобы проверить правильно ли работают вставки (работают). Затем я пытаюсь вставить ключ, который уже есть в дереве. Это приводит к seg-fault :( кто-нибудь может мне помочь? Это, вероятно, просто проблема с моим 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);