Check if removing an edge can divide a Binary Tree in two halves | Python3 program to check if there exist an edge whose removal creates two trees of same size utility function to create a new node ; To calculate size of tree with given root ; This function returns true if there is an edge whose removal can divide the tree in two halves n is size of tree ; Base cases ; Check for root ; Check for rest of the nodes ; This function mainly uses checkRec ( ) ; Count total nodes in given tree ; Now recursively check all nodes ; Driver code
class newNode : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def count ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( count ( root . left ) + count ( root . right ) + 1 ) NEW_LINE DEDENT def checkRec ( root , n ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( count ( root ) == n - count ( root ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return ( checkRec ( root . left , n ) or checkRec ( root . right , n ) ) NEW_LINE DEDENT def check ( root ) : NEW_LINE INDENT n = count ( root ) NEW_LINE return checkRec ( root , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 5 ) NEW_LINE root . left = newNode ( 1 ) NEW_LINE root . right = newNode ( 6 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . right . left = newNode ( 7 ) NEW_LINE root . right . right = newNode ( 4 ) NEW_LINE if check ( root ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT