mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
fix 101: refactor code
This commit is contained in:
@ -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)
|
||||
}
|
||||
|
Reference in New Issue
Block a user