-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
68 lines (53 loc) · 1.02 KB
/
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
func main() {
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func distanceK(root *TreeNode, target *TreeNode, k int) []int {
result = nil
runner(root, target, k)
return result
}
func runner(root, target *TreeNode, k int) (int, bool) {
if root == nil {
return -1, false
}
if target == root {
runnerChild(root, k)
return k - 1, true
}
newDist, ok := runner(root.Left, target, k)
if ok {
if newDist == 0 {
result = append(result, root.Val)
return -1, false
}
runnerChild(root.Right, newDist-1)
return newDist - 1, true
}
newDist, ok = runner(root.Right, target, k)
if ok {
if newDist == 0 {
result = append(result, root.Val)
return -1, false
}
runnerChild(root.Left, newDist-1)
return newDist - 1, true
}
return -1, false
}
var result []int
func runnerChild(root *TreeNode, k int) {
if root == nil || k < 0 {
return
}
if k == 0 {
result = append(result, root.Val)
return
}
runnerChild(root.Left, k-1)
runnerChild(root.Right, k-1)
}