day6 map附加: 二叉树排序算法

master
独孤伶俜 2022-11-20 17:04:23 +08:00
parent a8c6807aea
commit 575191ebde
1 changed files with 52 additions and 0 deletions

View File

@ -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)
}