Non | Non - recursive program to delete the 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 ; Driver program to test above functions ; create a binary tree ; delete entire binary tree
import java . util . * ; class Node { int data ; Node left , right ; public Node ( int data ) { this . data = data ; left = right = null ; } } class BinaryTree { Node root ; void _deleteTree ( ) { if ( root == null ) return ; Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; while ( ! q . isEmpty ( ) ) { Node node = q . peek ( ) ; q . poll ( ) ; if ( node . left != null ) q . add ( node . left ) ; if ( node . right != null ) q . add ( node . right ) ; } } void deleteTree ( ) { _deleteTree ( ) ; root = null ; } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 15 ) ; tree . root . left = new Node ( 10 ) ; tree . root . right = new Node ( 20 ) ; tree . root . left . left = new Node ( 8 ) ; tree . root . left . right = new Node ( 12 ) ; tree . root . right . left = new Node ( 16 ) ; tree . root . right . right = new Node ( 25 ) ; tree . deleteTree ( ) ; } }