A pointer to the root of the B-tree and a number to be inserted into the tree are passed to the function:

void bt_insert(Tree** tree_ptr, const int key); 

further, it looks for a node into which data can be inserted:

 if (!(*tree_ptr)->is_leaf) node = bt_get_node(*tree_ptr, key); else node = *tree_ptr; 

after inserting data into a tree, it is balanced if necessary

 if (node->count != DEGREE) return; bt_balance(&node); 

But in case you need to balance the root element, tree_ptr and node have different values. That is, if

 else node = *tree_ptr; 

That tree_ptr != &node

And I cannot insert another node instead of *tree_ptr in the bt_balance function (according to the algorithm).

What can be done here?

    1 answer 1

    If I understand you correctly, declare a node as

     Tree **node; 

    and use

     node = tree_ptr; 

    or one more fragment

     if ( ( *node )->count != DEGREE) return; bt_balance( node ); 

    In some places, you may need to declare another intermediate variable as

     Tree *tmp; 

    and use the design

     node = &tmp; 

    to pass a node to other functions that require a Tree ** object Tree **

    Or

     Tree *tmp; //... if (!(*tree_ptr)->is_leaf) tmp = bt_get_node(*tree_ptr, key); //... node = &tmp; 

    or depending on conditions

     node = tree_ptr; 
    • And what about node = bt_get_node(*tree_ptr, key); ? - zooZooz
    • @zooZooz See my updated answer. - Vlad from Moscow
    • there is still such a funny moment: Node* root = *tree_ptr; , but after that &root == tree_ptr returns 0 - zooZooz
    • @zooZooz As I already wrote it will be correct Node ** roort; root = tree_ptr; If you want to change the original pointers, then you need to declare a link to them and pass to other functions by reference. That is, you will need to use a double pointer. - Vlad from Moscow
    • can you please explain my 2 comment? I just don’t know what to do, my gap in theory with pointers to pointers does not allow to move on - zooZooz