Binary trees in C

I have the following code:

struct treenode;
typedef struct treenode* TreeNode;
struct treenode {
void* data;
TreeNode left, right;
};

TreeNode newTreeNode(void* data){
    TreeNode node = (TreeNode) malloc(sizeof(struct treenode));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}

bool insert(TreeNode tree, TreeNode node, int (*comp)(void*, void*)){
if(tree == NULL){
    tree = node;
    return true;
}
if(comp(node->data, tree->data) == 0){
    return false;
}
else if (comp(node->data, tree->data) < 0){
    insert((tree->left), node, comp);
}
else {
    insert((tree->right), node, comp);
}
return false;
}

int compare(void* i, void* j) {
if (*(int*)i < *(int*)j)
    return -1;
else if (*(int*)i == *(int*)j)
    return 0;
else
    return 1;
}

It works fine for 3 nodes, but when I try to insert more, it does not go past the first line of the tree (the line after the root), because it does not seem to have updated the root directory of the node, I think this is due to pointers in my method insertions, but I tried everything I could think of, and I still don't get anywhere.

Any help is greatly appreciated.

+3
source share
3 answers

You are editing only a local copy of the tree. Try:


bool insert(TreeNode* tree, TreeNode node, int (*comp)(void*, void*)){ 
if(*tree == NULL){ 
    *tree = node; 
    return true; 
} 
if(comp(node->data, (*tree)->data) == 0){ 
    return false; 
} 
else if (comp(node->data, (*tree)->data) < 0){ 
    insert((&((*tree)->left)), node, comp); 
} 
else { 
    insert((&((*tree)->right)), node, comp); 
} 
return false; 
}
+1
source
bool insert(TreeNode tree, TreeNode node, int (*comp)(void*, void*)){
if(tree == NULL){
    tree = node;
    return true;
}

(, , ) : tree treenode, node, , . -, - :

bool insert(TreeNode *tree, TreeNode node, int (*comp)(void *, void *)) { 
    if (*tree == NULL) {
        *tree = node;
        return true;
    }
// ....

, , .

node , node, ( ) node.

+1

You need a pointer to your Treenode to change it. Otherwise, you only modify the copy.


bool insert(TreeNode* tree, TreeNode node, int (comp)(void, void*)
+1
source

Source: https://habr.com/ru/post/1736333/


All Articles