forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.go
42 lines (42 loc) · 796 Bytes
/
Solution2.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
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isSameTree(p *TreeNode, q *TreeNode) bool {
if p == q {
return true
}
if p == nil || q == nil {
return false
}
q1 := []*TreeNode{p}
q2 := []*TreeNode{q}
for len(q1) > 0 && len(q2) > 0 {
p, q = q1[0], q2[0]
if p.Val != q.Val {
return false
}
q1, q2 = q1[1:], q2[1:]
la, ra := p.Left, p.Right
lb, rb := q.Left, q.Right
if (la != nil && lb == nil) || (lb != nil && la == nil) {
return false
}
if (ra != nil && rb == nil) || (rb != nil && ra == nil) {
return false
}
if la != nil {
q1 = append(q1, la)
q2 = append(q2, lb)
}
if ra != nil {
q1 = append(q1, ra)
q2 = append(q2, rb)
}
}
return true
}