Non | A binary tree node ; Non - recursive function to delete an entrie binary tree ; Base Case ; Create a empty queue for level order traversal ; Do level order traversal starting from root ; Deletes a tree and sets the root as None ; Create a binary tree ; delete entire binary tree
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def _deleteTree ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT node = q . pop ( 0 ) NEW_LINE if node . left is not None : NEW_LINE INDENT q . append ( node . left ) NEW_LINE DEDENT if node . right is not None : NEW_LINE INDENT q . append ( node . right ) NEW_LINE DEDENT node = None NEW_LINE DEDENT return node NEW_LINE DEDENT def deleteTree ( node_ref ) : NEW_LINE INDENT node_ref = _deleteTree ( node_ref ) NEW_LINE return node_ref NEW_LINE DEDENT root = Node ( 15 ) NEW_LINE root . left = Node ( 10 ) NEW_LINE root . right = Node ( 20 ) NEW_LINE root . left . left = Node ( 8 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . right . left = Node ( 16 ) NEW_LINE root . right . right = Node ( 25 ) NEW_LINE root = deleteTree ( root ) NEW_LINE