Skip to content

Commit 784e731

Browse files
committed
fix 101: refactor code
1 parent 09463ee commit 784e731

File tree

1 file changed

+11
-24
lines changed

1 file changed

+11
-24
lines changed

leetcode/0101.Symmetric-Tree/101. Symmetric Tree.go

Lines changed: 11 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,31 +17,18 @@ type TreeNode = structures.TreeNode
1717
*/
1818

1919
func isSymmetric(root *TreeNode) bool {
20-
if root == nil {
21-
return true
22-
}
23-
return isSameTree(invertTree(root.Left), root.Right)
24-
}
25-
26-
func isSameTree(p *TreeNode, q *TreeNode) bool {
27-
if p == nil && q == nil {
28-
return true
29-
} else if p != nil && q != nil {
30-
if p.Val != q.Val {
20+
var dfs func(rootLeft, rootRight *TreeNode) bool
21+
dfs = func(rootLeft, rootRight *TreeNode) bool {
22+
if rootLeft == nil && rootRight == nil {
23+
return true
24+
}
25+
if rootLeft == nil || rootRight == nil {
3126
return false
3227
}
33-
return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
34-
} else {
35-
return false
36-
}
37-
}
38-
39-
func invertTree(root *TreeNode) *TreeNode {
40-
if root == nil {
41-
return nil
28+
if rootLeft.Val != rootRight.Val {
29+
return false
30+
}
31+
return dfs(rootLeft.Left, rootRight.Right) && dfs(rootLeft.Right, rootRight.Left)
4232
}
43-
invertTree(root.Left)
44-
invertTree(root.Right)
45-
root.Left, root.Right = root.Right, root.Left
46-
return root
33+
return root == nil || dfs(root.Left, root.Right)
4734
}

0 commit comments

Comments
 (0)