golang[7]-数据结构-树的生成与遍历与通道遍历

node.go

节点的结构、打印节点、设置节点、遍历节点与通道遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package tree

import "fmt"

type Node struct {
Value int
Left, Right *Node
}

func (node Node) Print() {
fmt.Print(node.Value, " ")
}

func (node *Node) SetValue(value int) {
if node == nil {
fmt.Println("Setting Value to nil " +
"node. Ignored.")
return
}
node.Value = value
}

func CreateNode(value int) *Node {
return &Node{Value: value}
}


func (node *Node) Traverse() {
node.TraverseFunc(func(n *Node) {
n.Print()
})
fmt.Println()
}

func (node *Node) TraverseFunc(f func(*Node)) {
if node == nil {
return
}

node.Left.TraverseFunc(f)
f(node)
node.Right.TraverseFunc(f)
}

func (node *Node) TraverseWithChannel() chan *Node {
out := make(chan *Node)
go func() {
node.TraverseFunc(func(node *Node) {
out <- node
})
close(out)
}()
return out
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main

import (
"fmt"

"github/dreamjonson/tree"
)

type myTreeNode struct {
node *tree.Node
}

func (myNode *myTreeNode) postOrder() {
if myNode == nil || myNode.node == nil {
return
}

left := myTreeNode{myNode.node.Left}
right := myTreeNode{myNode.node.Right}

left.postOrder()
right.postOrder()
myNode.node.Print()
}

func main() {
//生成树
var root tree.Node

root = tree.Node{Value: 3}
root.Left = &tree.Node{}
root.Right = &tree.Node{5, nil, nil}
root.Right.Left = new(tree.Node)
root.Left.Right = tree.CreateNode(2)
root.Right.Left.SetValue(4)


//遍历树
fmt.Print("In-order traversal: ")
root.Traverse()

//遍历树2
fmt.Print("My own post-order traversal: ")
myRoot := myTreeNode{&root}
myRoot.postOrder()
fmt.Println()

//统计节点数量
nodeCount := 0
root.TraverseFunc(func(node *tree.Node) {
nodeCount++
})
fmt.Println("Node count:", nodeCount)

//通道遍历树
c := root.TraverseWithChannel()
maxNodeValue := 0
for node := range c {
if node.Value > maxNodeValue {
maxNodeValue = node.Value
}
}
fmt.Println("Max node value:", maxNodeValue)
}