From aafc29e534c965597c83559181bf739a99c173f3 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 24 Oct 2024 23:24:23 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB951.=20Flip=20Equivalent=20Bi?= =?UTF-8?q?nary=20Trees=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/flip-equivalent-binary-trees/ Signed-off-by: Matej Focko --- go/flip-equivalent-binary-trees.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 go/flip-equivalent-binary-trees.go 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 +}