二叉树的实现以及递归遍历(Golang)
欢迎指导
package main
import "fmt"
//定义树
type binarySearchTree struct {
value int
lchild, rchild *binarySearchTree
}
//新树
func NewBinarySearchTree(rootVal int) *binarySearchTree {
//如果不写全,要指定 Key
return &binarySearchTree{value:rootVal}
}
//插入树(把节点看成一个最简单的树)
func (bst *binarySearchTree) Insert(val int) *binarySearchTree {
if bst == nil {
return NewBinarySearchTree(val)
} else {
if val < bst.value {
bst.lchild = bst.lchild.Insert(val)
} else {
bst.rchild = bst.rchild.Insert(val)
}
return bst
}
}
//先序遍历
func (bst *binarySearchTree) PreOrder() {
if bst == nil {
return
} else {
fmt.Printf("%d", bst.value)
bst.lchild.PreOrder()
bst.rchild.PreOrder()
}
}
//中序遍历(从小到大排列)
func (bst *binarySearchTree) InOrder() {
if bst == nil {
return
} else {
bst.lchild.InOrder()
fmt.Printf("%d", bst.value)
bst.rchild.InOrder()
}
}
//后序遍历
func (bst *binarySearchTree) PostOrder() {
if bst == nil {
return
} else {
bst.lchild.PostOrder()
bst.rchild.PostOrder()
fmt.Printf("%d", bst.value)
}
}
func main() {
//定义切片存放树的元素
array := []int{6, 3, 8, 2, 5, 1, 7}
//定义bst指向一个二叉搜索树
var bst *binarySearchTree
//array --> tree
for _, v := range array {
bst = bst.Insert(v)
}
//遍历
bst.PreOrder()
fmt.Println()
bst.InOrder()
fmt.Println()
bst.PostOrder()
}