-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsolution.go
More file actions
67 lines (54 loc) · 1.13 KB
/
solution.go
File metadata and controls
67 lines (54 loc) · 1.13 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package symmetric_tree
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func isSymmetricBfs(root *TreeNode) bool {
if root.Left == nil && root.Right == nil {
return true
}
q := []*TreeNode{}
q = append(q, root)
for len(q) != 0 {
qLen := len(q)
checks := []int{}
for i := 0; i < qLen; i++ {
cur := q[0]
q = q[1:]
if cur.Left != nil {
q = append(q, cur.Left)
checks = append(checks, cur.Left.Val)
} else {
checks = append(checks, -1)
}
if cur.Right != nil {
q = append(q, cur.Right)
checks = append(checks, cur.Right.Val)
} else {
checks = append(checks, -1)
}
}
for i := 0; i < len(checks)/2; i++ {
if checks[i] != checks[len(checks)-1-i] {
return false
}
}
}
return true
}
func isSymmetricDfs(root *TreeNode) bool {
return isMirror(root.Left, root.Right)
}
func isMirror(left *TreeNode, right *TreeNode) bool {
if left == nil && right == nil {
return true
}
if left == nil || right == nil {
return false
}
if left.Val != right.Val {
return false
}
return isMirror(left.Left, right.Right) && isMirror(left.Right, right.Left)
}