Check if a Binary Tree consists of a pair of leaf nodes with sum K | Stores if a pair exists or not ; Struct binary tree node ; Function to check if a pair of leaf nodes exists with sum K ; Checks if root is NULL ; Checks if the current node is a leaf node ; Checks for a valid pair of leaf nodes ; Insert value of current node into the set ; Traverse left and right subtree ; Driver Code ; Construct binary tree ; Stores the leaf nodes
pairFound = False NEW_LINE S = set ( ) NEW_LINE 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 pairSum ( root , target ) : NEW_LINE INDENT global pairFound NEW_LINE global S NEW_LINE if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT temp = list ( S ) NEW_LINE if ( temp . count ( target - root . data ) ) : NEW_LINE INDENT print ( target - root . data , root . data ) NEW_LINE pairFound = True NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT S . add ( root . data ) NEW_LINE DEDENT DEDENT pairSum ( root . left , target ) NEW_LINE pairSum ( root . right , target ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . right . right . right = newNode ( 8 ) NEW_LINE K = 13 NEW_LINE pairSum ( root , K ) NEW_LINE if ( pairFound == False ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT