Find K smallest leaf nodes from a given Binary Tree | Binary tree node ; Function to create new node ; Utility function which calculates smallest three nodes of all leaf nodes ; Check if current root is a leaf node ; Traverse the left and right subtree ; Function to find the K smallest nodes of the Binary Tree ; Sorting the Leaf nodes array ; Loop to print the K smallest Leaf nodes of the array ; Driver Code ; Construct binary tree ; Function Call
class Node : 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 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 storeLeaf ( root : Node , arr : list ) -> None : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( not root . left and not root . right ) : NEW_LINE INDENT arr . append ( root . data ) NEW_LINE return NEW_LINE DEDENT storeLeaf ( root . left , arr ) NEW_LINE storeLeaf ( root . right , arr ) NEW_LINE DEDENT def KSmallest ( root : Node , k : int ) -> None : NEW_LINE INDENT arr = [ ] NEW_LINE storeLeaf ( root , arr ) NEW_LINE arr . sort ( ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( i < len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . left . left = Node ( 21 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . left . right . right = Node ( 8 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE root . right . right . right = Node ( 19 ) NEW_LINE KSmallest ( root , 3 ) NEW_LINE DEDENT