golang簡單實現二叉樹的數據添加和遍歷
阿新 • • 發佈:2019-02-26
package empty pty testin 廣度 golang his 數據 imp
代碼實現
package tree import "fmt" type Node struct { elem interface{} left, right *Node } type Tree struct { root *Node } func NewTree() *Tree { return &Tree{} } // 添加元素 func (this *Tree) Add(v interface{}) { node := &Node{elem: v} if this.root == nil { this.root = node return } c := make(chan *Node, 10) c <- this.root for len(c) > 0 { curNode := <-c if curNode.left == nil { curNode.left = node return } else { c <- curNode.left } if curNode.right == nil { curNode.right = node return } else { c <- curNode.right } } } // 廣度優先遍歷 func (this *Tree) Travel() { if this.root == nil { fmt.Println("empty tree") return } c := make(chan *Node, 10) c <- this.root for len(c) > 0 { curNode := <-c fmt.Println(curNode.elem) if curNode.left != nil { c <- curNode.left } if curNode.right != nil { c <- curNode.right } } } // 先序遍歷 func (this *Tree) Xianxu() { xz(this.root) } // 中序遍歷 func (this *Tree) ZhongXu() { zx(this.root) } // 後序遍歷 func (this *Tree) HouXu() { hx(this.root) } func xz(node *Node) { if node == nil { return } fmt.Println(node.elem) xz(node.left) xz(node.right) } func zx(node *Node) { if node == nil { return } zx(node.left) fmt.Println(node.elem) zx(node.right) } func hx(node *Node) { if node == nil { return } hx(node.left) hx(node.right) fmt.Println(node.elem) }
測試
package tree import "testing" var tree *Tree func prepare() { tree = NewTree() tree.Add("mark") tree.Add("jack") tree.Add("timo") tree.Add("marry") tree.Add("toshiyuki") tree.Add("naruto") tree.Add("sakura") } func TestTree_Travel(t *testing.T) { prepare() tree.Travel() } func TestTree_Xianxu(t *testing.T) { prepare() tree.Xianxu() } func TestTree_ZhongXu(t *testing.T) { prepare() tree.ZhongXu() } func TestTree_HouXu(t *testing.T) { prepare() tree.HouXu() }
測試結果
=== RUN TestTree_Travel mark jack timo marry toshiyuki naruto sakura --- PASS: TestTree_Travel (0.00s) === RUN TestTree_Xianxu mark jack marry toshiyuki timo naruto sakura --- PASS: TestTree_Xianxu (0.00s) === RUN TestTree_ZhongXu marry jack toshiyuki mark naruto timo sakura --- PASS: TestTree_ZhongXu (0.00s) === RUN TestTree_HouXu marry toshiyuki jack naruto sakura timo mark --- PASS: TestTree_HouXu (0.00s) PASS
golang簡單實現二叉樹的數據添加和遍歷