-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
63 lines (50 loc) · 788 Bytes
/
main.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
package main
func main() {
}
type Node struct {
Val int
Left *Node
Right *Node
Parent *Node
}
func lowestCommonAncestor(p *Node, q *Node) *Node {
if getLCA(p, q) {
return p
}
if getLCA(q, p) {
return q
}
m = make(map[*Node]bool)
return getParentPath(p, q)
}
var m = map[*Node]bool{}
func getParentPath(p, q *Node) *Node {
if p == nil && q == nil {
return nil
}
if m[p] {
return p
}
if p != nil {
m[p] = true
}
if m[q] {
return q
}
if q != nil {
m[q] = true
}
if p == nil {
return getParentPath(p, q.Parent)
}
if q == nil {
return getParentPath(p.Parent, q)
}
return getParentPath(p.Parent, q.Parent)
}
func getLCA(f, s *Node) bool {
if f == nil {
return false
}
return f == s || getLCA(f.Left, s) || getLCA(f.Right, s)
}