golang简单实现二叉树的数据添加和遍历
Posted endurance9
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang简单实现二叉树的数据添加和遍历相关的知识,希望对你有一定的参考价值。
代码实现
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简单实现二叉树的数据添加和遍历的主要内容,如果未能解决你的问题,请参考以下文章
数据结构初阶第八篇——二叉树的链式结构(二叉树的前中和后序遍历+层序遍历+链式结构的实现+相关简单的递归问题)