-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree.go
66 lines (59 loc) · 947 Bytes
/
binary-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
63
64
65
66
package main
import (
"fmt"
)
type Node struct{
data int
left * Node
right * Node
}
func (n* Node) insert(data int) error {
if data < n.data {
if n.left == nil {
n.left = &Node{data, nil, nil}
return nil
}
return n.left.insert(data)
} else {
if n.right == nil {
n.right = &Node{data, nil, nil}
return nil
}
return n.right.insert(data)
}
}
func (root *Node) diameter() int {
if root == nil {
return 0
}
maxLength := 0
depth(root, &maxLength)
return(maxLength)
}
func depth(root *Node, maxLength *int) int {
if root == nil {
return 0
}
l := depth(root.left, maxLength)
r := depth(root.right, maxLength)
*maxLength = Max(l + r, *maxLength)
return Max(l, r) + 1
}
func Max(a, b int)int{
if a >= b{
return a
}else{
return b
}
}
func main(){
x := &Node{8,nil,nil}
x.insert(2)
x.insert(1)
x.insert(4)
x.insert(16)
x.insert(32)
x.insert(64)
x.insert(0)
fmt.Println(x.diameter() + 1)
}