-
Notifications
You must be signed in to change notification settings - Fork 0
/
101.go
108 lines (91 loc) · 1.72 KB
/
101.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
# ------------------------------ #
# #
# version 0.0.1 #
# #
# Aleksiej Ostrowski, 2022 #
# #
# https://aleksiej.com #
# #
# ------------------------------ #
*/
package main
import (
"fmt"
)
/**
* Definition for a binary tree node.
*/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func isSameTree(p *TreeNode, q *TreeNode) bool {
if (p == nil) && (q == nil) {
return true
}
curr1 := p
curr2 := q
for {
if (curr1 == nil) || (curr2 == nil) {
if curr1 != curr2 {
return false
}
break
}
if (curr1.Left == nil) || (curr2.Left == nil) {
if curr1.Left != curr2.Left {
return false
}
if curr1.Val != curr2.Val {
return false
}
curr1 = curr1.Right
curr2 = curr2.Right
} else {
pre1 := curr1.Left
pre2 := curr2.Left
for {
if (pre1.Right == nil) || (pre2.Right == nil) {
if pre1.Right != pre2.Right {
return false
}
break
}
pre1 = pre1.Right
pre2 = pre2.Right
}
pre1.Right = curr1
temp1 := curr1
curr1 = curr1.Left
temp1.Left = nil
pre2.Right = curr2
temp2 := curr2
curr2 = curr2.Left
temp2.Left = nil
}
}
return true
}
func exchangeLeftAndRight(root *TreeNode) {
if root == nil {
return
}
temp := root.Right
root.Right = root.Left
root.Left = temp
exchangeLeftAndRight(root.Right)
exchangeLeftAndRight(root.Left)
}
func isSymmetric(root *TreeNode) bool {
a := root.Right
b := root.Left
exchangeLeftAndRight(a)
return isSameTree(a, b)
}
func main() {
tree := &TreeNode{0, nil, nil}
res := isSymmetric(tree)
fmt.Println(res)
}