Deleting a binary tree using the delete keyword in C++?

C++Server Side ProgrammingProgramming

<p>Let us first define our binary tree using a class containing int data, btree_node * rightChild, btree_node * leftChild. The leftChild and rightChild are pointers to btree_node. All the members in our class are public.</p><pre class="prettyprint notranslate">class btree_node { &nbsp; &nbsp;public: &nbsp; &nbsp; &nbsp; int data; &nbsp; &nbsp; &nbsp; btree_node* leftChild; &nbsp; &nbsp; &nbsp; btree_node* rightChild;</pre><p>For creating a new node we have the constructor function that takes the int value as parameter to assign it to the newly created node value. The leftChild and rightChild are set to null.</p><pre class="prettyprint notranslate">btree_node(int data){ &nbsp; &nbsp;this-&gt;data = data; &nbsp; &nbsp;this-&gt;leftChild = NULL; &nbsp; &nbsp;this-&gt; = NULL; }</pre><p>The class deconstructor deletes the left and right child of the binary tree using the delete keyword when being invoked.</p><pre class="prettyprint notranslate">~btree_node(){ &nbsp; &nbsp;delete leftChild; &nbsp; &nbsp;delete rightChild; &nbsp; &nbsp;cout &lt;&lt; this-&gt;data &lt;&lt; &quot;is being deleted&quot;&lt;&lt;endl; }</pre><p>To trigger the deletion of the tree we call the delete on the root node as its left and right subtree will be deleted along.</p><pre class="prettyprint notranslate">delete root;</pre><h2>Example</h2><p>Let us see the following implementation for deleting binary tree using the delete keyword &minus;</p><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include &lt;iostream&gt; using namespace std; class btree_node { &nbsp; &nbsp;public: &nbsp; &nbsp;int data; &nbsp; &nbsp;btree_node* leftChild; &nbsp; &nbsp;btree_node* rightChild; &nbsp; &nbsp;btree_node(int data){ &nbsp; &nbsp; &nbsp; this-&gt;data = data; &nbsp; &nbsp; &nbsp; this-&gt;leftChild = NULL; &nbsp; &nbsp; &nbsp; this-&gt;rightChild = NULL; &nbsp; &nbsp;} &nbsp; &nbsp;~btree_node(){ &nbsp; &nbsp; &nbsp; delete leftChild; &nbsp; &nbsp; &nbsp; delete rightChild; &nbsp; &nbsp; &nbsp; cout &lt;&lt; this-&gt;data &lt;&lt; &quot; is being deleted&quot;&lt;&lt;endl; &nbsp; &nbsp;} }; int main(){ &nbsp; &nbsp;btree_node* root = new btree_node(2); &nbsp; &nbsp;btree_node* node1 = new btree_node(4); &nbsp; &nbsp;btree_node* node2 = new btree_node(6); &nbsp; &nbsp;btree_node* node3 = new btree_node(8); &nbsp; &nbsp;btree_node* node4 = new btree_node(10); &nbsp; &nbsp;root-&gt;leftChild = node1; &nbsp; &nbsp;root-&gt;rightChild = node2; &nbsp; &nbsp;node1-&gt;leftChild = node3; &nbsp; &nbsp;node1-&gt;rightChild = node4; &nbsp; &nbsp;delete root; &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><p>The above code will produce the following output &minus;</p><pre class="result notranslate">8 is being deleted 10 is being deleted 4 is being deleted 6 is being deleted 2 is being deleted</pre>
Updated on 16-Jan-2021 07:32:09