day6 map附加: 二叉树排序算法
parent
a8c6807aea
commit
575191ebde
|
@ -0,0 +1,52 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
type tree struct {
|
||||||
|
value int
|
||||||
|
left, right *tree
|
||||||
|
}
|
||||||
|
|
||||||
|
func Sort(values []int) {
|
||||||
|
var root *tree
|
||||||
|
for _, v := range values {
|
||||||
|
root = add(root, v)
|
||||||
|
//fmt.Println(root.value)
|
||||||
|
}
|
||||||
|
// 将二叉树还原为切片
|
||||||
|
appendValues(values[:0], root)
|
||||||
|
}
|
||||||
|
func appendValues(values []int, t *tree) []int {
|
||||||
|
if t != nil {
|
||||||
|
values = appendValues(values, t.left)
|
||||||
|
values = append(values, t.value)
|
||||||
|
values = appendValues(values, t.right)
|
||||||
|
}
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
// 建树
|
||||||
|
func add(t *tree, value int) *tree {
|
||||||
|
if t == nil {
|
||||||
|
t = new(tree)
|
||||||
|
t.value = value
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
if value < t.value {
|
||||||
|
t.left = add(t.left, value)
|
||||||
|
//fmt.Println("left", t.value)
|
||||||
|
} else {
|
||||||
|
t.right = add(t.right, value)
|
||||||
|
//fmt.Println("right", t.value)
|
||||||
|
}
|
||||||
|
//fmt.Println(value)
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var nums []int = []int{4, 5, 43, 323, 45, 98, 4, 5, 7, 8, 1, 3, 2, 565}
|
||||||
|
fmt.Println(nums)
|
||||||
|
Sort(nums)
|
||||||
|
fmt.Println(nums)
|
||||||
|
}
|
Loading…
Reference in New Issue