-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathmain.go
More file actions
73 lines (67 loc) · 1.15 KB
/
main.go
File metadata and controls
73 lines (67 loc) · 1.15 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
73
package main
import (
"fmt"
"log"
"math/rand"
"time"
)
// Tree structure
type Tree struct {
Left *Tree
Value int
Right *Tree
}
/**
* While traversing on a binary tree
*/
func traverse(t *Tree) {
if t == nil {
return
}
traverse(t.Left)
log.Print(t.Value, "")
traverse(t.Right)
}
/**
* Creating a binary tree with random value
*/
func create(n int) *Tree {
var t *Tree
// Logic to insert random int value
rand.Seed(time.Now().Unix())
for i := 0; i < 2*n; i++ {
temp := rand.Intn(n * 2)
// invoking insert function to create form a binary tree
t = insert(t, temp)
}
return t
}
/**
* Inserting random values in a tree
*/
func insert(t *Tree, v int) *Tree {
if t == nil {
return &Tree{nil, v, nil}
}
if v == t.Value {
return t
}
if v < t.Value {
t.Left = insert(t.Left, v)
return t
}
t.Right = insert(t.Right, v)
return t
}
// Main function invocation
func main() {
tree := create(30)
fmt.Println("The value of the root of the tree is", tree.Value)
traverse(tree)
fmt.Println()
tree = insert(tree, -10)
tree = insert(tree, -2)
traverse(tree)
fmt.Println()
fmt.Println("The value of the root of the tree is", tree.Value)
}