-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst.go
More file actions
72 lines (55 loc) · 1.25 KB
/
bst.go
File metadata and controls
72 lines (55 loc) · 1.25 KB
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
package main
import (
"fmt"
"math/rand"
"time"
)
type Node struct{
left *Node
right *Node
value int
child bool
}
func insert(root *Node, v int){
if root==(&Node{}){
*root=Node{nil,nil,v,true}
}else if v > root.value { //right node
if root.right != nil {insert(root.right, v)
}else{root.right=&Node{nil,nil,v,true}}
}else if v < root.value { //left node
if root.left != nil {
insert(root.left, v)
}else{root.left=&Node{nil,nil,v,true}}
}
}
func traverse(root *Node) {
if root!=nil{
if root.left != nil {traverse(root.left)}
// fmt.Print(root.value," ")
if root.right != nil {traverse(root.right)}
}
}
func main() {
root:=new(Node)
const SIZE = 900000
var a [SIZE]int
fmt.Printf("Generating random array with %v values...\n", SIZE)
start := time.Now()
for i := 0; i < SIZE; i++ {
a[i] = rand.Intn(SIZE)
}
end := time.Since(start)
fmt.Printf("Done. Took %s\n\n", end)
fmt.Printf("Filling the tree with %v nodes...\n", SIZE)
start = time.Now()
for i := 0; i < SIZE; i++ {
insert(root, a[i])
}
end = time.Since(start)
fmt.Printf("Done. Took %s\n\n", end)
fmt.Printf("Traversing all %v nodes in tree...\n", SIZE)
start = time.Now()
traverse(root)
end = time.Since(start)
fmt.Printf("Done. Took %s\n\n", end)
}