Refactored solution 101

This commit is contained in:
Breno Baptista
2021-06-20 19:53:41 -03:00
parent 75b8f85315
commit 804bf60609

View File

@ -16,51 +16,22 @@ type TreeNode = structures.TreeNode
* }
*/
// 解法一 dfs
func isMirror(left *TreeNode, right *TreeNode) bool {
if left == nil && right == nil {
return true
}
if left == nil || right == nil {
return false
}
return (left.Val == right.Val) && isMirror(left.Left, right.Right) && isMirror(left.Right, right.Left)
}
func isSymmetric(root *TreeNode) bool {
return root == nil || dfs(root.Left, root.Right)
}
func dfs(rootLeft, rootRight *TreeNode) bool {
if rootLeft == nil && rootRight == nil {
return true
}
if rootLeft == nil || rootRight == nil {
return false
}
if rootLeft.Val != rootRight.Val {
return false
}
return dfs(rootLeft.Left, rootRight.Right) && dfs(rootLeft.Right, rootRight.Left)
}
// 解法二
func isSymmetric1(root *TreeNode) bool {
if root == nil {
return true
}
return isSameTree(invertTree(root.Left), root.Right)
}
func isSameTree(p *TreeNode, q *TreeNode) bool {
if p == nil && q == nil {
return true
} else if p != nil && q != nil {
if p.Val != q.Val {
return false
}
return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
} else {
return false
}
}
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
invertTree(root.Left)
invertTree(root.Right)
root.Left, root.Right = root.Right, root.Left
return root
return isMirror(root.Left, root.Right)
}