Remove nodes on root to leaf paths of length < K | New node of a tree ; Utility method that actually removes the nodes which are not on the pathLen >= k . This method can change the root as well . ; Base condition ; Traverse the tree in postorder fashion so that if a leaf node path length is shorter than k , then that node and all of its descendants till the node which are not on some other path are removed . ; If root is a leaf node and it 's level   is less than k then remove this node.   This goes up and check for the ancestor   nodes also for the same condition till  it finds a node which is a part of other   path(s) too.  ; Return root ; Method which calls the utitlity method to remove the short path nodes . ; Method to print the tree in inorder fashion . ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def removeShortPathNodesUtil ( root , level , k ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT root . left = removeShortPathNodesUtil ( root . left , level + 1 , k ) NEW_LINE root . right = removeShortPathNodesUtil ( root . right , level + 1 , k ) NEW_LINE if ( root . left == None and root . right == None and level < k ) : NEW_LINE INDENT return None NEW_LINE DEDENT return root NEW_LINE DEDENT def removeShortPathNodes ( root , k ) : NEW_LINE INDENT pathLen = 0 NEW_LINE return removeShortPathNodesUtil ( root , 1 , k ) NEW_LINE DEDENT def prInorder ( root ) : NEW_LINE INDENT if ( root ) : NEW_LINE INDENT prInorder ( root . left ) NEW_LINE print ( root . data , end = " ▁ " ) NEW_LINE prInorder ( root . right ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 4 NEW_LINE root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . left . left . left = newNode ( 7 ) NEW_LINE root . right . right = newNode ( 6 ) NEW_LINE root . right . right . left = newNode ( 8 ) NEW_LINE print ( " Inorder ▁ Traversal ▁ of ▁ Original ▁ tree " ) NEW_LINE prInorder ( root ) NEW_LINE print ( ) NEW_LINE print ( " Inorder ▁ Traversal ▁ of ▁ Modified ▁ tree " ) NEW_LINE res = removeShortPathNodes ( root , k ) NEW_LINE prInorder ( res ) NEW_LINE DEDENT