-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_search_tree.go
62 lines (49 loc) · 977 Bytes
/
binary_search_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
package binarysearchtree
type SearchTreeData struct {
left *SearchTreeData
data int
right *SearchTreeData
}
func Bst(data int) *SearchTreeData {
return &SearchTreeData{nil, data, nil}
}
func (s *SearchTreeData) Insert(data int) {
td := &SearchTreeData{nil, data, nil}
p := s
for p != nil {
if data > p.data {
if p.right == nil {
p.right = td
break
}
p = p.right
} else {
if p.left == nil {
p.left = td
break
}
p = p.left
}
}
}
func (s *SearchTreeData) MapString(fn func(int) string) []string {
ints := walkTree(s)
res := make([]string, len(ints))
for i, v := range ints {
res[i] = fn(v)
}
return res
}
func (s *SearchTreeData) MapInt(fn func(int) int) []int {
return walkTree(s)
}
func walkTree(s *SearchTreeData) []int {
if s == nil {
return nil
}
ints := make([]int, 0)
ints = append(ints, walkTree(s.left)...)
ints = append(ints, s.data)
ints = append(ints, walkTree(s.right)...)
return ints
}