Note that there are some explanatory texts on larger screens.

plurals
  1. POnon recursive binary tree insert() method not working
    primarykey
    data
    text
    <p>I have written a binary tree code for inserting elements into it in non-recursive method. The code is not working as intended. Regardless of how many times I debug the code, nothing seems to be wrong but I am getting wrong results. I am hoping you guys can help. Thanks in advance.</p> <pre><code>void insert(int element){ if(root == NULL){ struct elemq *node; node = (struct elemq *)malloc(sizeof(struct elemq)); node-&gt;ele = element; node-&gt;left = NULL; node-&gt;right = NULL; root = node; cout &lt;&lt; root-&gt;ele &lt;&lt; "\n"; } else{ struct elemq *ref; ref = root; while(ref != NULL){ if(element &lt;= ref-&gt;ele){ if(ref-&gt;left == NULL){ struct elemq *node; node = (struct elemq *)malloc(sizeof(struct elemq )); node-&gt;ele = element; node-&gt;left = NULL; node-&gt;right = NULL; ref-&gt;left = node; break; } else{ ref = ref-&gt;left; } } else if(element &gt; ref-&gt;ele){ if(ref-&gt;right == NULL){ struct elemq *node; node = (struct elemq *)malloc(sizeof(struct elemq )); node-&gt;ele = element; node-&gt;left = NULL; node-&gt;right = NULL; ref-&gt;right = node; break; } else{ ref = ref-&gt;right; } } } } } </code></pre> <p>Every time I try to insert an element, each element is being treated as <code>root</code>, not only the first time. So, every time, the condition <code>if(root == NULL)</code> is <code>true</code>. I declared <code>root</code> as global variable and initialized it to <code>NULL</code> in <code>main()</code>. I came to know this by putting <code>cout &lt;&lt;</code> in the first <code>if()</code> condition. I modified my previous post to this new question.</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