golang二叉樹中序遍歷操做節點

直接上代碼node

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()
}

 運行結果:blog

相關文章
相關標籤/搜索