直接上代码
package tree import ( "fmt" ) //定义node节点结构体 type Node struct { Value int Left, Right *Node } //node.Print方法打印节点Value func (node Node) Print() { fmt.Print(node.Value) } //node.SetValue设置节点Value func (node *Node) SetValue(value int) { node.Value =value } //中序遍历操作方法,根据传入的函数中序遍历节点做特定操作 func (node *Node) TraverseFunc(f func(node *Node)){ if node == nil{ return } node.Left.TraverseFunc(f) f(node) node.Right.TraverseFunc(f) } //方法中序打印Value func (node *Node) Traverse() { node.TraverseFunc(func(n *Node) { n.Print() }) } //工厂函数 func CreateNode(value int) *Node { return &Node{Value: value} }
mian函数(打印节点Value):
package main import "tree" 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) root.Traverse() }
运行结果: