Note that there are some explanatory texts on larger screens.

plurals
  1. POInserting 4 or 5 numbers in binary tree but getting just 3 numbers in the output
    text
    copied!<p>This is part of a lab for school dealing with recursion and binary tree. If I go to insert 4 or 5 numbers and output the result I get just 3 numbers back. Here is the code for insert:</p> <pre><code>Node *insert(Node *t, int key) { Node *insertParent; Node *result=NULL; if (t!=NULL) { result=search(t,key,insertParent); } else { t=new Node; t-&gt;data=key; t-&gt;leftchild=NULL; t-&gt;rightchild=NULL; return t; } if (result==NULL) { if (insertParent-&gt;data&gt;key) { insertParent-&gt;leftchild=new Node; insertParent-&gt;leftchild-&gt;data=key; insertParent-&gt;leftchild-&gt;leftchild=NULL; insertParent-&gt;leftchild-&gt;rightchild=NULL; return insertParent-&gt;leftchild; } else if (insertParent-&gt;data&lt;key) { insertParent-&gt;rightchild=new Node; insertParent-&gt;rightchild-&gt;data=key; insertParent-&gt;rightchild-&gt;leftchild=NULL; insertParent-&gt;rightchild-&gt;rightchild=NULL; return insertParent-&gt;rightchild; } } else return NULL; } </code></pre> <p>But I believe the trouble is within the search function, specifically the node pointer by reference parent:</p> <pre><code>Node* search(Node *t, int key, Node *&amp;parent) { if (t!=NULL) { parent=t; if (t-&gt;data==key) return t; else if (t-&gt;data&gt;key) return search(t-&gt;leftchild,key,t); else return search(t-&gt;rightchild,key,t); } else return NULL; } </code></pre> <p>I have a function that outputs the tree and have checked it against a tree I built manually and it works fine:</p> <pre><code>void inorder(Node *t) { if (t!=NULL) { if (t-&gt;leftchild!=NULL) inorder(t-&gt;leftchild); cout &lt;&lt; t-&gt;data &lt;&lt; ", "; if (t-&gt;rightchild!=NULL) inorder(t-&gt;rightchild); } } </code></pre> <p>Not looking for an answer just looking for an area I should look at.</p>
 

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