defdfs(left, right): # if one of the nodes does not exist ifnot left ornot right: return left == right # if nodes are not equal if left.val != right.val: returnFalse # check their children symmetrically return dfs(left.left, right.right) and dfs(left.right, right.left)
while ltree and rtree: iflen(ltree) != len(rtree): returnFalse for i inrange(len(ltree)): left, right = ltree.pop(0), rtree.pop(0) ifnot left andnot right: continue ifnot left ornot right: returnFalse if left.val != right.val: returnFalse ltree.append(left.left) ltree.append(left.right) rtree.append(right.right) rtree.append(right.left)