-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminimal_ht_tree2.go
70 lines (58 loc) · 1.37 KB
/
minimal_ht_tree2.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
package main
/*
* Given a sorted array increasing order of unique integers,
* create a binary search tree with minimal height.
*/
import (
"binary_tree/tree"
"fmt"
"math"
"os"
"sort"
"strconv"
)
func minHeightInsert(sortedArray []int) (root *tree.NumericNode) {
root = nil
if sz := len(sortedArray); sz > 0 {
middle := sz / 2
root = &tree.NumericNode{Data: sortedArray[middle]}
root.Left = minHeightInsert(sortedArray[0:middle])
root.Right = minHeightInsert(sortedArray[middle+1:])
}
return root
}
func main() {
sortedArray := make([]int, 0)
N := 1
outputGraphViz := false
if os.Args[1] == "-g" {
N = 2
outputGraphViz = true
}
for _, str := range os.Args[N:] {
val, err := strconv.Atoi(str)
if err == nil {
sortedArray = append(sortedArray, val)
}
}
sort.Sort(sort.IntSlice(sortedArray))
fmt.Printf("/* Sorted array: %v */\n", sortedArray)
root := minHeightInsert(sortedArray)
if root != nil {
depth, _ := tree.FindDepth2(root, 1)
D := math.Log2(float64(len(sortedArray)) + 1.0)
f := float64(depth)
if f >= D && f <= D+1.0 {
fmt.Printf("/* minimal height tree %.3f <= %.3f <= %.3f */\n", D, f, D+1.0)
}
fmt.Printf("/* In order traverse: ")
tree.InorderTraverse(root)
fmt.Printf(" */\n")
if outputGraphViz {
tree.Draw(root)
}
if tree.BstProperty(root) {
fmt.Printf("/* This is a binary search tree */\n")
}
}
}