這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
現在只實現了很簡單的增加、尋找、遍曆。後面有空會完善。
package mainimport "fmt"type BNode struct {data intleft *BNoderight *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}// 返回nodefunc (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 = newNodereturn}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))}