go: add «951. Flip Equivalent Binary Trees»

URL:	https://leetcode.com/problems/flip-equivalent-binary-trees/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-10-24 23:24:23 +02:00
parent 29f2194d56
commit aafc29e534
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -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
}