Remove all subtrees consisting only of even valued nodes from a Binary Tree | Java program for the above approach ; Node of the tree ; Function to create a new node ; Function to print tree level wise ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root ; Print front of queue and remove it from queue ; If left child is present ; Otherwise ; If right child is present ; Otherwise ; Function to remove subtrees ; Base Case ; Search for required condition in left and right half ; If the node is even and leaf node ; Driver Code ; Function Call ; Print answer
import java . util . * ; class GFG { static class node { int data ; node left , right ; } ; static node newNode ( int key ) { node temp = new node ( ) ; temp . data = key ; temp . left = temp . right = null ; return ( temp ) ; } static void printLevelOrder ( node root ) { if ( root == null ) return ; Queue < node > q = new LinkedList < > ( ) ; q . add ( root ) ; while ( ! q . isEmpty ( ) ) { node temp = q . peek ( ) ; System . out . print ( temp . data + " ▁ " ) ; q . remove ( ) ; if ( temp . left != null ) { q . add ( temp . left ) ; } else if ( temp . right != null ) { System . out . print ( " null ▁ " ) ; } if ( temp . right != null ) { q . add ( temp . right ) ; } else if ( temp . left != null ) { System . out . print ( " null ▁ " ) ; } } } static node pruneTree ( node root ) { if ( root == null ) { return null ; } root . left = pruneTree ( root . left ) ; root . right = pruneTree ( root . right ) ; if ( root . data % 2 == 0 && root . right == null && root . left == null ) return null ; return root ; } public static void main ( String [ ] args ) { node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . left . left = newNode ( 8 ) ; root . left . right = newNode ( 10 ) ; root . right = newNode ( 7 ) ; root . right . left = newNode ( 12 ) ; root . right . right = newNode ( 5 ) ; node newRoot = pruneTree ( root ) ; printLevelOrder ( newRoot ) ; } }