Note that there are some explanatory texts on larger screens.

plurals
  1. POBinary Trees in C
    primarykey
    data
    text
    <p>I'm trying to insert nodes into a tree in order. My function works fine... when there's only three nodes.</p> <p>I have this code:</p> <pre><code>typedef struct _Tnode Tnode; struct _Tnode { char* data; Tnode* left; Tnode* right; }; </code></pre> <p>Along with this:</p> <pre><code>Tnode* add_tnode(Tnode* current_node, char* value) { Tnode* ret_value; if(current_node == NULL) { current_node = (Tnode*) malloc(sizeof(Tnode)); if(current_node != NULL) { (current_node)-&gt;data = value; (current_node)-&gt;left = NULL; (current_node)-&gt;right = NULL; ret_value = current_node; } else printf("no memory"); } else { if(strcmp(current_node-&gt;data,value)) { //left for less than ret_value = add_tnode((current_node-&gt;left), value); current_node -&gt; left = (Tnode*) malloc(sizeof(Tnode)); (current_node -&gt; left) -&gt; data = value; } else if(strcmp(current_node-&gt;data,value) &gt; 0) { ret_value = add_tnode((current_node -&gt; right), value); current_node -&gt; right = (Tnode*) malloc(sizeof(Tnode)); (current_node -&gt; right) -&gt; data = value; } else { printf("duplicate\n"); ret_value = current_node; } } return ret_value; </code></pre> <p>}</p> <p>I know what's wrong here, I just don't know how to fix it. This just overwrites the two nodes attached to the root node. i.e.</p> <pre><code> |root_node| / \ |node_2| |node_3| </code></pre> <p>I can't add a node four. It just overwrites node 2 or 3 depending on the input. After debugging and a little research, I'm not quite sure where to go from here...</p> <p>If anyone can help, I'd really appreciate it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload