package main
import (
“fmt”
“math/rand”
“time”
)
//定义节点结构体
type Tree struct{
Left *Tree
Value int
Right *Tree
}
//打印二叉树
func printTree(t *Tree) {
if t ==nil{
return
}
//这里使用前序遍历打印数据,这里有不懂的,可以搜索一下,前序,中序,后序遍历
printTree(t.Left)
fmt.Println(t.Value,” “)
printTree(t.Right)
}
//创建节点
func create(n int ) *Tree {
var t *Tree
rand.Seed(time.Now().Unix())
for i := 0; i < 2*n; i++ {
temp :=rand.Intn(n*2)
t =insert(t,temp)
}
return t
}
//向节点里添加数据
func insert(t *Tree ,v int) *Tree {
if t==nil{
return &Tree{
Left: nil,
Value: v,
Right: nil,
}
}
if t.Value==v{
return t
}
if v<t.Value{
t.Left=insert(t.Left,v)
return t
}
t.Right=insert(t.Right,v)
return t
}
func main() {
tree := create(3)
fmt.Println(“树结节数据”,tree.Value)
printTree(tree)
//fmt.Println()
tree = insert(tree,-10)
tree = insert(tree,-2)
printTree(tree)
//fmt.Println()
//fmt.Println(“添加后的数据节点值”,tree.Value)
}