Golang program to implement Binary Tree
生活随笔
收集整理的這篇文章主要介紹了
Golang program to implement Binary Tree
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??
A binary tree is a tree data structure in which each node has at most two child nodes, usually distinguished as "left" and "right". Nodes with children are parent nodes, and child nodes may contain references to their parents. Here is the source code of the Go program to implement Binary Tree
// Binary Tree in Golangpackage mainimport ("fmt""os""io")type BinaryNode struct {left? *BinaryNoderight *BinaryNodedata? int64}type BinaryTree struct {root *BinaryNode}func (t *BinaryTree) insert(data int64) *BinaryTree {if t.root == nil {t.root = &BinaryNode{data: data, left: nil, right: nil}} else {t.root.insert(data)}return t}func (n *BinaryNode) insert(data int64) {if n == nil {return} else if data <= n.data {if n.left == nil {n.left = &BinaryNode{data: data, left: nil, right: nil}} else {n.left.insert(data)}} else {if n.right == nil {n.right = &BinaryNode{data: data, left: nil, right: nil}} else {n.right.insert(data)}}??}func print(w io.Writer, node *BinaryNode, ns int, ch rune) {if node == nil {return}for i := 0; i < ns; i++ {fmt.Fprint(w, " ")}fmt.Fprintf(w, "%c:%v\n", ch, node.data)print(w, node.left, ns+2, 'L')print(w, node.right, ns+2, 'R')}func main() {tree := &BinaryTree{}tree.insert(100).insert(-20).insert(-50).insert(-15).insert(-60).insert(50).insert(60).insert(55).insert(85).insert(15).insert(5).insert(-10)print(os.Stdout, tree.root, 0, 'M')} C:\golang\time>go run binarytree.go M:100 L:-20 L:-50 L:-60 R:-15 R:50 L:15 L:5 L:-10 R:60 L:55 R:85C:\golang\time>?
轉(zhuǎn)載于:https://my.oschina.net/tsh/blog/1634100
總結(jié)
以上是生活随笔為你收集整理的Golang program to implement Binary Tree的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 函数式和面向对象
- 下一篇: poj2823 Sliding Wind