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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
package main
import "fmt"
type Node struct {
parent *Node
left *Node
right *Node
val int
isLeft bool
}
func (n *Node) pushLeft(val int) {
n.left = &Node{
parent: n,
val: val,
isLeft: true,
}
}
func (n *Node) pushRight(val int) {
n.right = &Node{
parent: n,
val: val,
isLeft: false,
}
}
func (n *Node) maxDepth(depth int) int {
if n == nil {
return depth
}
return max(n.left.maxDepth(depth+1), n.right.maxDepth(depth+1))
}
func (n *Node) find(target int) *Node {
if n == nil {
return nil
}
if n.val == target {
return n
}
l := n.left.find(target)
if l != nil {
return l
}
return n.right.find(target)
}
func (n *Node) radial(nodes *[]*Node, distance int, fromTarget bool, fromChild bool, fromLeft bool) {
if n == nil {
return
}
if distance == 0 {
*nodes = append(*nodes, n)
return
}
if fromChild {
if fromLeft {
n.right.radial(nodes, distance-1, false, false, false)
} else {
n.left.radial(nodes, distance-1, false, false, false)
}
n.parent.radial(nodes, distance-1, false, true, n.isLeft)
} else {
n.left.radial(nodes, distance-1, false, false, false)
n.right.radial(nodes, distance-1, false, false, false)
}
if fromTarget {
n.parent.radial(nodes, distance-1, false, true, n.isLeft)
}
}
func main() {
root := Node{
val: 1,
}
root.pushRight(2)
root.right.pushLeft(3)
root.right.pushRight(4)
root.pushLeft(5)
root.left.pushLeft(6)
root.left.pushRight(7)
root.left.left.pushLeft(8)
root.left.left.pushRight(9)
root.left.right.pushLeft(10)
root.left.right.pushRight(11)
find := root.find(5)
fmt.Println(find)
nodes := []*Node{}
find.radial(&nodes, 2, true, false, false)
fmt.Println(nodes)
for _, node := range nodes {
fmt.Println(node.val)
}
}
|