diff --git a/go/flip-equivalent-binary-trees.go b/go/flip-equivalent-binary-trees.go new file mode 100644 index 0000000..6f5b204 --- /dev/null +++ b/go/flip-equivalent-binary-trees.go @@ -0,0 +1,26 @@ +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 +}