Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You're have both a design flaw and an outright-bug in your loop. </p> <p>The design flaw: You're allocating a new node, but assigning to <code>cursor</code> doesn't mean you're assigning to the parent node left or right child pointer that got you there in the first place. You need a reference to the actual pointer you're going to populate. One way to do this is with a pointer-to-pointer, and as a bonus, this eliminates the is-my-root-null check at the beginning. </p> <p>The outright bug: Your left-side movement clause (i.e. chasing a left-side pointer) will potentially change <code>cursor</code> to NULL. but the logic for chasing the right side is not excluded with an <em>else if</em> condition. If your search followed a left-side to null it would fault chasing the right side of a null pointer. This was obviously a problem.</p> <pre><code>void add(int value, Tree *t) { Node **pp = &amp;(t-&gt;root); while (*pp) { if(value == (*pp)-&gt;value) { printf("value already present in BST\n"); return; } if(value &lt; (*pp)-&gt;value) pp = &amp;(*pp)-&gt;left; else if(value &gt; (*pp)-&gt;value) pp = &amp;(*pp)-&gt;right; } *pp = nodeCreate(value); t-&gt;size++; } </code></pre> <p>I should also note that you can skip the equality check by assuming a strict-weak order. I.e. the following rule can be considered valid:</p> <pre><code>if (!(a &lt; b) &amp;&amp; !(b &lt; a)) then a == b is true. </code></pre> <p>That makes your insertion simpler as well.</p> <pre><code>void add(int value, Tree *t) { Node **pp = &amp;(t-&gt;root); while (*pp) { if (value &lt; (*pp)-&gt;value) pp = &amp;(*pp)-&gt;left; else if ((*pp)-&gt;value &lt; value) pp = &amp;(*pp)-&gt;right; else { // must be equal. printf("value already present in BST\n"); return; } } *pp = nodeCreate(value); t-&gt;size++; } </code></pre>
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      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