Remove all leaf nodes from the binary search tree | Python 3 program to delete leaf Node from binary search tree . Create a newNode in binary search tree . ; Constructor to create a new node ; Insert a Node in binary search tree . ; Function for inorder traversal in a BST . ; Delete leaf nodes from binary search tree . ; Else recursively delete in left and right subtrees . ; Driver code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( root , data ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return newNode ( data ) NEW_LINE DEDENT if data < root . data : NEW_LINE INDENT root . left = insert ( root . left , data ) NEW_LINE DEDENT elif data > root . data : NEW_LINE INDENT root . right = insert ( root . right , data ) NEW_LINE DEDENT return root NEW_LINE DEDENT def inorder ( root ) : NEW_LINE INDENT if root != None : NEW_LINE INDENT inorder ( root . left ) NEW_LINE print ( root . data , end = " ▁ " ) NEW_LINE inorder ( root . right ) NEW_LINE DEDENT DEDENT def leafDelete ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return None NEW_LINE DEDENT if root . left == None and root . right == None : NEW_LINE INDENT return None NEW_LINE DEDENT root . left = leafDelete ( root . left ) NEW_LINE root . right = leafDelete ( root . right ) NEW_LINE return root NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 20 ) NEW_LINE insert ( root , 10 ) NEW_LINE insert ( root , 5 ) NEW_LINE insert ( root , 15 ) NEW_LINE insert ( root , 30 ) NEW_LINE insert ( root , 25 ) NEW_LINE insert ( root , 35 ) NEW_LINE print ( " Inorder ▁ before ▁ Deleting ▁ the ▁ leaf ▁ Node . " ) NEW_LINE inorder ( root ) NEW_LINE leafDelete ( root ) NEW_LINE print ( ) NEW_LINE print ( " INorder ▁ after ▁ Deleting ▁ the ▁ leaf ▁ Node . " ) NEW_LINE inorder ( root ) NEW_LINE DEDENT