Matej Focko
aafc29e534
URL: https://leetcode.com/problems/flip-equivalent-binary-trees/ Signed-off-by: Matej Focko <me@mfocko.xyz>
26 lines
516 B
Go
26 lines
516 B
Go
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
|
|
}
|