Note that there are some explanatory texts on larger screens.

plurals
  1. PODeep Copy Constructor for binary tree
    primarykey
    data
    text
    <p>I am trying to create a deep copy of my binary tree data structure in C++. The problem is the code I am using only seems to be giving me a shallow copy (which seems to cause problems with my deconstructor). </p> <p>the code below is my binary tree copy constructor:</p> <pre><code>BinaryTreeStorage::BinaryTreeStorage(const BinaryTreeStorage &amp;copytree):root(NULL) { root = copytree.root; copyTree(root); } BinaryTreeStorage::node* BinaryTreeStorage::copyTree(node* other) { //if node is empty (at bottom of binary tree) /* This creates a shallow copy which in turn causes a problem with the deconstructor, could not work out how to create a deep copy. */ if (other == NULL) { return NULL; } node* newNode = new node; if (other -&gt;nodeValue == "") { newNode -&gt;nodeValue = ""; } newNode-&gt;left = copyTree(other-&gt;left); newNode-&gt;right = copyTree(other-&gt;right); return newNode; } </code></pre> <p>Any help would be appreciated. Thanks</p> <p>Here is the deconstructor that throws a memory exception (which i believe is because of the shallow copy i do above)</p> <pre><code>BinaryTreeStorage::~BinaryTreeStorage(void) { try { destroy_tree();//Call the destroy tree method delete root;//delete final node } catch(int &amp;error) { cout &lt;&lt; "Error Message : " &lt;&lt; error &lt;&lt; endl; } } void BinaryTreeStorage::destroy_tree() { destroy_tree(root); } void BinaryTreeStorage::destroy_tree(node *leaf) { if(leaf!=NULL) { //Recursively work way to bottom node destroy_tree(leaf-&gt;left); destroy_tree(leaf-&gt;right); //delete node delete leaf; } } </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.
 

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