fix 101: refactor code

This commit is contained in:
h30003300
2021-04-17 10:39:43 +08:00
parent 09463eee6f
commit 784e731c77

View File

@ -17,31 +17,18 @@ type TreeNode = structures.TreeNode
*/
func isSymmetric(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 {
var dfs func(rootLeft, rootRight *TreeNode) bool
dfs = func(rootLeft, rootRight *TreeNode) bool {
if rootLeft == nil && rootRight == nil {
return true
}
if rootLeft == nil || rootRight == nil {
return false
}
return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
} else {
return false
if rootLeft.Val != rootRight.Val {
return false
}
return dfs(rootLeft.Left, rootRight.Right) && dfs(rootLeft.Right, rootRight.Left)
}
}
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 root == nil || dfs(root.Left, root.Right)
}