package main

func flipEquiv(left, right *TreeNode) bool {
	// reached leaves
	if left == nil && right == nil {
		return true
	}

	// reached only one leaf
	if left == nil || right == nil {
		return false
	}

	// can't build equivalent subtrees
	if left.Val != right.Val {
		return false
	}

	// no swap
	isEquiv := flipEquiv(left.Left, right.Left) && flipEquiv(left.Right, right.Right)

	// with swap
	isEquiv = isEquiv || (flipEquiv(left.Left, right.Right) && flipEquiv(left.Right, right.Left))

	return isEquiv
}