Print the Forests of a Binary Tree after removal of given Nodes | Java Program to implement the above approach ; Stores the nodes to be deleted ; Structure of a Tree node ; Function to create a new node ; Function to check whether the node needs to be deleted or not ; Function to perform tree pruning by performing post order traversal ; If the node needs to be deleted ; Store the its subtree ; Perform Inorder Traversal ; Function to print the forests ; Stores the remaining nodes ; Print the inorder traversal of Forests ; Driver Code
import java . util . * ; class GFG { static HashMap < Integer , Boolean > mp = new HashMap < > ( ) ; static class Node { int key ; Node left , right ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . left = temp . right = null ; return ( temp ) ; } static boolean deleteNode ( int nodeVal ) { return mp . containsKey ( nodeVal ) ; } static Node treePruning ( Node root , Vector < Node > result ) { if ( root == null ) return null ; root . left = treePruning ( root . left , result ) ; root . right = treePruning ( root . right , result ) ; if ( deleteNode ( root . key ) ) { if ( root . left != null ) { result . add ( root . left ) ; } if ( root . right != null ) { result . add ( root . right ) ; } return null ; } return root ; } static void printInorderTree ( Node root ) { if ( root == null ) return ; printInorderTree ( root . left ) ; System . out . print ( root . key + " ▁ " ) ; printInorderTree ( root . right ) ; } static void printForests ( Node root , int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { mp . put ( arr [ i ] , true ) ; } Vector < Node > result = new Vector < > ( ) ; if ( treePruning ( root , result ) != null ) result . add ( root ) ; for ( int i = 0 ; i < result . size ( ) ; i ++ ) { printInorderTree ( result . get ( i ) ) ; System . out . println ( ) ; } } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 12 ) ; root . right = newNode ( 13 ) ; root . right . left = newNode ( 14 ) ; root . right . right = newNode ( 15 ) ; root . right . left . left = newNode ( 21 ) ; root . right . left . right = newNode ( 22 ) ; root . right . right . left = newNode ( 23 ) ; root . right . right . right = newNode ( 24 ) ; int arr [ ] = { 14 , 23 , 1 } ; int n = arr . length ; printForests ( root , arr , n ) ; } }