@@ -16,51 +16,22 @@ type TreeNode = structures.TreeNode
16
16
* }
17
17
*/
18
18
19
- // 解法一 dfs
20
- func isSymmetric (root * TreeNode ) bool {
21
- return root == nil || dfs (root .Left , root .Right )
22
- }
23
-
24
- func dfs (rootLeft , rootRight * TreeNode ) bool {
25
- if rootLeft == nil && rootRight == nil {
19
+ func isMirror (left * TreeNode , right * TreeNode ) bool {
20
+ if left == nil && right == nil {
26
21
return true
27
22
}
28
- if rootLeft == nil || rootRight == nil {
29
- return false
30
- }
31
- if rootLeft .Val != rootRight .Val {
23
+
24
+ if left == nil || right == nil {
32
25
return false
33
26
}
34
- return dfs (rootLeft .Left , rootRight .Right ) && dfs (rootLeft .Right , rootRight .Left )
35
- }
36
27
37
- // 解法二
38
- func isSymmetric1 (root * TreeNode ) bool {
39
- if root == nil {
40
- return true
41
- }
42
- return isSameTree (invertTree (root .Left ), root .Right )
28
+ return (left .Val == right .Val ) && isMirror (left .Left , right .Right ) && isMirror (left .Right , right .Left )
43
29
}
44
30
45
- func isSameTree ( p * TreeNode , q * TreeNode ) bool {
46
- if p == nil && q == nil {
31
+ func isSymmetric ( root * TreeNode ) bool {
32
+ if root == nil {
47
33
return true
48
- } else if p != nil && q != nil {
49
- if p .Val != q .Val {
50
- return false
51
- }
52
- return isSameTree (p .Left , q .Left ) && isSameTree (p .Right , q .Right )
53
- } else {
54
- return false
55
34
}
56
- }
57
35
58
- func invertTree (root * TreeNode ) * TreeNode {
59
- if root == nil {
60
- return nil
61
- }
62
- invertTree (root .Left )
63
- invertTree (root .Right )
64
- root .Left , root .Right = root .Right , root .Left
65
- return root
36
+ return isMirror (root .Left , root .Right )
66
37
}
0 commit comments