Check if two BSTs contain same set of elements | BST Node ; Utility function to create Node ; function to insert elements of the tree to map m ; function to check if the two BSTs contain same set of elements ; Base cases ; Create two hash sets and store elements both BSTs in them . ; Return True if both hash sets contain same elements . ; First BST ; Second BST ; check if two BSTs have same set of elements
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . val = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def Node_ ( val1 ) : NEW_LINE INDENT temp = Node ( ) NEW_LINE temp . val = val1 NEW_LINE temp . left = temp . right = None NEW_LINE return temp NEW_LINE DEDENT v = [ ] NEW_LINE def storeInorder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT storeInorder ( root . left ) NEW_LINE v . append ( root . data ) NEW_LINE storeInorder ( root . right ) NEW_LINE DEDENT def checkBSTs ( root1 , root2 ) : NEW_LINE INDENT if ( root1 != None and root2 != None ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( ( root1 == None and root2 != None ) or ( root1 != None and root2 == None ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE v = v1 NEW_LINE storeInorder ( root1 ) NEW_LINE v1 = v NEW_LINE v = v2 NEW_LINE storeInorder ( root2 ) NEW_LINE v2 = v NEW_LINE return ( v1 == v2 ) NEW_LINE DEDENT root1 = Node_ ( 15 ) NEW_LINE root1 . left = Node_ ( 10 ) NEW_LINE root1 . right = Node_ ( 20 ) NEW_LINE root1 . left . left = Node_ ( 5 ) NEW_LINE root1 . left . right = Node_ ( 12 ) NEW_LINE root1 . right . right = Node_ ( 25 ) NEW_LINE root2 = Node_ ( 15 ) NEW_LINE root2 . left = Node_ ( 12 ) NEW_LINE root2 . right = Node_ ( 20 ) NEW_LINE root2 . left . left = Node_ ( 5 ) NEW_LINE root2 . left . left . right = Node_ ( 10 ) NEW_LINE root2 . right . right = Node_ ( 25 ) NEW_LINE if ( checkBSTs ( root1 , root2 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT