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
mp = dict ( ) NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE return temp NEW_LINE DEDENT def deleteNode ( nodeVal ) : NEW_LINE INDENT if nodeVal in mp : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def treePruning ( root , result ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None ; NEW_LINE DEDENT root . left = treePruning ( root . left , result ) ; NEW_LINE root . right = treePruning ( root . right , result ) ; NEW_LINE if ( deleteNode ( root . key ) ) : NEW_LINE INDENT if ( root . left ) : NEW_LINE INDENT result . append ( root . left ) ; NEW_LINE DEDENT if ( root . right ) : NEW_LINE INDENT result . append ( root . right ) ; NEW_LINE DEDENT return None ; NEW_LINE DEDENT return root ; NEW_LINE DEDENT def printInorderTree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return ; NEW_LINE DEDENT printInorderTree ( root . left ) ; NEW_LINE print ( root . key , end = ' ▁ ' ) NEW_LINE printInorderTree ( root . right ) ; NEW_LINE DEDENT def printForests ( root , arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] = True ; NEW_LINE DEDENT result = [ ] NEW_LINE if ( treePruning ( root , result ) ) : NEW_LINE INDENT result . append ( root ) ; NEW_LINE DEDENT for i in range ( len ( result ) ) : NEW_LINE INDENT printInorderTree ( result [ i ] ) ; NEW_LINE print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) ; NEW_LINE root . left = newNode ( 12 ) ; NEW_LINE root . right = newNode ( 13 ) ; NEW_LINE root . right . left = newNode ( 14 ) ; NEW_LINE root . right . right = newNode ( 15 ) ; NEW_LINE root . right . left . left = newNode ( 21 ) ; NEW_LINE root . right . left . right = newNode ( 22 ) ; NEW_LINE root . right . right . left = newNode ( 23 ) ; NEW_LINE root . right . right . right = newNode ( 24 ) ; NEW_LINE arr = [ 14 , 23 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE printForests ( root , arr , n ) ; NEW_LINE DEDENT