对称二叉树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main

import "fmt"

type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}

func isSymmetric(root *TreeNode) bool {
if root == nil {
return true
}
return isMirror(root.Left, root.Right)
}

func isMirror(left, 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 main() {
// 创建一个对称二叉树
root := &TreeNode{Val: 1}
root.Left = &TreeNode{Val: 2}
root.Right = &TreeNode{Val: 2}
root.Left.Left = &TreeNode{Val: 3}
root.Left.Right = &TreeNode{Val: 4}
root.Right.Left = &TreeNode{Val: 4}
root.Right.Right = &TreeNode{Val: 3}

// 判断二叉树是否对称
result := isSymmetric(root)

// 输出结果
fmt.Println(result)
}