# 封装
```go
type TreeNode struct {
Left, Right *TreeNode
Value int
}
//值接收者和指针接收者和传参数类型没有什么区别
//如果要改变内容或内容比较大,建议用值接收者
func (root *TreeNode) traverse() {
if root == nil {
return
}
root.Left.traverse()
fmt.Print(root.Value, " ")
root.Right.traverse()
}
func createTreeNode(v int) *TreeNode {
return &TreeNode{Value: v}
}
func main() {
var root TreeNode
root = TreeNode{Value: 3}
root.Left = createTreeNode(4)
root.Right = &TreeNode{Value: 5}
root.Left.Right = createTreeNode(2)
root.Right.Left = createTreeNode(8)
root.traverse()
}
```
# 扩展已有类型
```go
type TreeNode struct {
Left, Right *TreeNode
Value int
}
//值接收者和指针接收者和传参数类型没有什么区别
//如果要改变内容或内容比较大,建议用值接收者
func (root *TreeNode) traverse() {
if root == nil {
return
}
root.Left.traverse()
root.print()
root.Right.traverse()
}
func (root *TreeNode) print() {
fmt.Print(root.Value, " ")
}
type myTreeNode struct {
node *TreeNode
}
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 createTreeNode(v int) *TreeNode {
return &TreeNode{Value: v}
}
func main() {
var root TreeNode
root = TreeNode{Value: 3}
root.Left = createTreeNode(4)
root.Right = &TreeNode{Value: 5}
root.Left.Right = createTreeNode(2)
root.Right.Left = createTreeNode(8)
root.traverse()
fmt.Println()
myroot := myTreeNode{&root}
myroot.postOrder()
}
```
有疑问加站长微信联系(非本文作者))