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:
parent
29f2194d56
commit
aafc29e534
1 changed files with 26 additions and 0 deletions
26
go/flip-equivalent-binary-trees.go
Normal file
26
go/flip-equivalent-binary-trees.go
Normal 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
|
||||||
|
}
|
Loading…
Reference in a new issue