Skip to content

Instantly share code, notes, and snippets.

@wangyiyang
Created December 23, 2019 03:15
Show Gist options
  • Save wangyiyang/0b60fb7462a881bdbd7d60c4c25b4bb4 to your computer and use it in GitHub Desktop.
Save wangyiyang/0b60fb7462a881bdbd7d60c4c25b4bb4 to your computer and use it in GitHub Desktop.
二叉树排序 #Golang #Algorithm
package main
import "fmt"
type tree struct {
value int
left, right *tree
}
func Sort(values []int) []int {
var root *tree
for _, v := range values {
root = add(root, v)
}
return 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)
} else {
t.right = add(t.right, value)
}
return t
}
func main() {
a := []int{1, 4, 3, 6, 5, 7, 9, 2}
fmt.Println(Sort(a))
}
// [1 2 3 4 5 6 7 9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment