-
Notifications
You must be signed in to change notification settings - Fork 1
/
binarytree.go
91 lines (75 loc) · 1.24 KB
/
binarytree.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package gods
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func (t *TreeNode) Insert(val int) {
if t.Val < val {
// move right
if t.Right == nil {
t.Right = &TreeNode{Val: val}
} else {
t.Right.Insert(val)
}
} else {
// move left
if t.Left == nil {
t.Left = &TreeNode{Val: val}
} else {
t.Left.Insert(val)
}
}
}
func (t *TreeNode) Search(val int) bool {
if t == nil {
return false
}
if t.Val < val {
return t.Right.Search(val)
} else {
return t.Left.Search(val)
}
return true
}
func (t *TreeNode) Delete(val int) {
if t == nil {
return
}
if t.Val < val {
t.Right.Delete(val)
} else {
t.Left.Delete(val)
}
if t.Left == nil && t.Right == nil {
t = nil
}
}
// Source: halfrost
func Ints2TreeNode(ints []int) *TreeNode {
n := len(ints)
if n == 0 {
return nil
}
root := &TreeNode{
Val: ints[0],
}
queue := make([]*TreeNode, 1, n*2)
queue[0] = root
i := 1
for i < n {
node := queue[0]
queue = queue[1:]
if i < n && ints[i] != Null {
node.Left = &TreeNode{Val: ints[i]}
queue = append(queue, node.Left)
}
i++
if i < n && ints[i] != Null {
node.Right = &TreeNode{Val: ints[i]}
queue = append(queue, node.Right)
}
i++
}
return root
}