现在只实现了很简单的增加、查找、遍历。后面有空会完善。
package main
import "fmt"
type BNode struct {
data int
left *BNode
right *BNode
}
type Tree struct {
FirstNode *BNode
}
func (t *Tree) PrintData (node *BNode) {
if node.left != nil {
t.PrintData(node.left)
}
fmt.Println(node.data)
if node.right != nil {
t.PrintData(node.right)
}
return
}
// 返回node
func (t *Tree) Search(data int, bnode *BNode) *BNode {
if bnode == nil {
return nil
}
if data > bnode.data {
return t.Search(data, bnode.right)
} else if data < bnode.data {
return t.Search(data, bnode.left)
} else if data == bnode.data {
return bnode
}
return nil
}
func (t *Tree) Insert(data int, currentNode *BNode) {
newNode := &BNode{
data,
nil,
nil,
}
if t.FirstNode == nil {
t.FirstNode = newNode
return
}
if t.Search(data, t.FirstNode) != nil {
panic("该数据已经存在")
return
}
if data > currentNode.data {
if currentNode.right == nil {
currentNode.right = newNode
} else {
t.Insert(data,currentNode.right)
}
} else if data < currentNode.data {
if currentNode.left == nil {
currentNode.left = newNode
} else {
t.Insert(data, currentNode.left)
}
}
return
}
func main() {
nodes := []int{4,1,7,15,10}
tree := Tree{}
for _, data := range nodes {
tree.Insert(data, tree.FirstNode)
}
tree.PrintData(tree.FirstNode)
fmt.Print(tree.Search(10, tree.FirstNode))
}
有疑问加站长微信联系(非本文作者)