Print the Forests of a Binary Tree after removal of given Nodes | 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
let mp = new Map ( ) ; class Node { constructor ( key ) { this . left = this . right = null ; this . key = key ; } } function newNode ( key ) { let temp = new Node ( key ) ; return ( temp ) ; } function deleteNode ( nodeVal ) { return mp . has ( nodeVal ) ; } function treePruning ( root , 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 . push ( root . left ) ; } if ( root . right != null ) { result . push ( root . right ) ; } return null ; } return root ; } function printInorderTree ( root ) { if ( root == null ) return ; printInorderTree ( root . left ) ; document . write ( root . key + " " ) ; printInorderTree ( root . right ) ; } function printForests ( root , arr , n ) { for ( let i = 0 ; i < n ; i ++ ) { mp . set ( arr [ i ] , true ) ; } let result = [ ] ; if ( treePruning ( root , result ) != null ) result . push ( root ) ; for ( let i = 0 ; i < result . length ; i ++ ) { printInorderTree ( result [ i ] ) ; document . write ( " " ) ; } } let 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 ) ; let arr = [ 14 , 23 , 1 ] ; let n = arr . length ; printForests ( root , arr , n ) ;