二叉树是每个节点最多有两个分支的数据结构,树的根节点是树结构的第一个节点,树的深度也叫树的高度:是从树的根节点到所有节点的路径中最长的一个.而节点的深度是该节点到树的根所经过的路径中边的数量
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.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)
}