go二叉树排序

    二叉树排序:一种基于二叉树的排序算法。

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)
    }
     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 () {
     values := [] int { 4 , 5 , 3 , 6 , 1 , 8 , 7 , 9 , 0 , 2 }
     Sort (values)
    fmt. Printf ( "%d \n " , values)
}

猜你喜欢

转载自blog.csdn.net/u013235495/article/details/80526699