- Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsymmetric_tree.go
77 lines (62 loc) · 1.64 KB
/
symmetric_tree.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
package main
// Definition for a binary tree node.
typeTreeNodestruct {
Valint
Left*TreeNode
Right*TreeNode
}
varanswerbool
// Recursive
funcisSymmetrics(root*TreeNode) bool {
// Runtime: 3 ms, faster than 70.37% of Go online submissions for Symmetric Tree.
// Memory Usage: 2.9 MB, less than 83.92% of Go online submissions for Symmetric Tree.
varanswerbool=true
ifroot!=nil {
findSymmetricity(root.Left, root.Right)
}
returnanswer
}
funcfindSymmetricity(firstNode, secondNode*TreeNode) {
iffirstNode==nil&&secondNode==nil||answer==false {
return
}
iffirstNode==nil||secondNode==nil||firstNode.Val!=secondNode.Val {
answer=false
return
}
findSymmetricity(firstNode.Left, secondNode.Right)
findSymmetricity(firstNode.Right, secondNode.Left)
}
funcisSymmetric(root*TreeNode) bool {
// Runtime: 0 ms, faster than 100.00% of Go online submissions for Symmetric Tree.
// Memory Usage: 2.9 MB, less than 19.79% of Go online submissions for Symmetric Tree.
ifroot==nil {
returntrue
}
stack:=make([]*TreeNode, 2)
stack[0] =root
stack[1] =root
forlen(stack) >0 {
n:=len(stack) -1
firstNode:=stack[n]
// rewrite
stack=stack[:n]
n=len(stack) -1
secondNode:=stack[n]
stack=stack[:n]
iffirstNode==nil&&secondNode==nil {
continue
}
iffirstNode==nil||secondNode==nil {
returnfalse
}
iffirstNode.Val!=secondNode.Val {
returnfalse
}
stack=append(stack, firstNode.Left)
stack=append(stack, secondNode.Right)
stack=append(stack, firstNode.Right)
stack=append(stack, secondNode.Left)
}
returntrue
}