代码实现
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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步