Non | Non - Recursive Program to delete an entire binary tree . ; A Binary Tree Node ; Non - recursive function to delete an entire binary tree . ; Base Case ; Create an empty queue for level order traversal ; Do level order traversal starting from root ; Deletes a tree and sets the root as NULL ; Utility function to create a new tree Node ; Driver program to test above functions ; create a binary tree ; delete entire binary tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; void _deleteTree ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { Node * node = q . front ( ) ; q . pop ( ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; free ( node ) ; } } void deleteTree ( Node * * node_ref ) { _deleteTree ( * node_ref ) ; * node_ref = NULL ; } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { Node * root = newNode ( 15 ) ; root -> left = newNode ( 10 ) ; root -> right = newNode ( 20 ) ; root -> left -> left = newNode ( 8 ) ; root -> left -> right = newNode ( 12 ) ; root -> right -> left = newNode ( 16 ) ; root -> right -> right = newNode ( 25 ) ; deleteTree ( & root ) ; return 0 ; }