title: Repair tree structure in c
body: <p>I have a tree structure in c (quadtree) which I want to clean to avoid long tree branches. Here is an example:</p>
  
  <p>Instead of this tree structure,</p>
  
  <p><a href="https://i.stack.imgur.com/aujoW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aujoW.png" alt="enter image description here"></a></p>
  
  <p>I want to clean up the tree to get this structure (Same information, less memory consumption, faster tree walks).</p>
  
  <p><a href="https://i.stack.imgur.com/eN8xY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eN8xY.png" alt="enter image description here"></a></p>
  
  <p>Here the red node is the root of the tree. Blue nodes are empty and black nodes are tree nodes which carry information.</p>
  
  <p>My tree has the following structure in c:</p>
  
  <pre><code>typedef enum{particle, pseudo_particle} node_type;
  
  typedef struct{
      double m;
      double x[DIM];
      int to_delete;
  } Particle;
  
  typedef struct{
      double x_min[DIM];
      double x_max[DIM];
  } tree_box;
  
  typedef struct tree_node{
      Particle p;
      tree_box box;
      node_type node;
      struct tree_node *child[4];
  } tree_node;
  </code></pre>
  
  <p>The function which cleans up the tree</p>
  
  <pre><code>void clean_tree(tree_node *t){
      if(t != NULL){
          for(int i=0; i&lt;4; i++){
              clean_tree(t-&gt;child[i]);
          }
          // Operation on *t
          if(t-&gt;node != particle){
              int child_counter = 0;
              int d = 0;
              for(int i=0; i&lt;4; i++) {
                  if(t-&gt;child[i] != NULL) {
                      if(t-&gt;child[i]-&gt;p.to_delete == TRUE){
                          free(t-&gt;child[i]);
                          t-&gt;child[i] = NULL;
                      }
                      else {
                          child_counter++;
                          d=i;
                      }
                  }
              }
  
              if(child_counter == 0) {
                  t-&gt;p.to_delete = TRUE;
              }else if (child_counter == 1) {
                  t = t-&gt;child[d];
                  free(t-&gt;child[d]);
                  t-&gt;child[d] = NULL;
              }
          }
          // End of operation on *t
      }
  }
  </code></pre>
  
  <p>But here is the problem: After calling clean_tree() my tree structure is no longer existent. The whole tree gets deleted. But why? Does someone see my error?</p>