-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
68 lines (55 loc) · 887 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
64
65
66
67
68
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello world")
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func findDistance(root *TreeNode, p int, q int) int {
if p == q {
return 0
}
lca := LCA(root, p, q)
l, _ := getDist(lca, q)
r, _ := getDist(lca, p)
return l + r
}
func getDist(root *TreeNode, p int) (int, bool) {
if root == nil {
return 0, false
}
if root.Val == p {
return 0, true
}
l, okL := getDist(root.Left, p)
if okL {
return l + 1, true
}
r, okR := getDist(root.Right, p)
if okR {
return r + 1, true
}
return 0, false
}
func LCA(root *TreeNode, p, q int) *TreeNode {
if root == nil {
return nil
}
if root.Val == p || root.Val == q {
return root
}
l := LCA(root.Left, p, q)
r := LCA(root.Right, p, q)
if l != nil && r != nil {
return root
}
if r != nil {
return r
}
return l
}