** tree包**
```
package tree
import (
"log"
)
// Binary Tree
type BinaryTree struct {
Data interface{}
Left *BinaryTree
Right *BinaryTree
}
// 先序遍历 - 递归
func (bt *BinaryTree)PreOrderRec(v []interface{}) {
if bt == nil {
return
}
log.Println("current data :",bt.Data)
v = append(v,bt.Data)
log.Println("v : ",v)
bt.Left.PreOrderRec(v)
bt.Right.PreOrderRec(v)
}
```
** main 包 **
```
package main
import(
"tree"
"log"
)
func main() {
//创建一颗树
root := tree.BinaryTree{"A", nil, nil}
root.Left = &tree.BinaryTree{Data:"B"}
root.Right = &tree.BinaryTree{Data:"C"}
root.Left.Left = &tree.BinaryTree{Data:"D"}
root.Left.Right = &tree.BinaryTree{Data:"F"}
root.Left.Right.Left = new(tree.BinaryTree)
root.Left.Right.Left.Data = "E"
root.Right.Left = &tree.BinaryTree{Data:"G"}
root.Right.Left.Right = &tree.BinaryTree{Data:"H"}
root.Right.Right = &tree.BinaryTree{Data:"I"}
str := make([]interface{},0)
root.PreOrderRec(str)
log.Println(str)
}
```
**输出的str结果**
```
2019/08/21 23:23:28 current data : A
2019/08/21 23:23:28 v : [A]
2019/08/21 23:23:28 current data : B
2019/08/21 23:23:28 v : [A B]
2019/08/21 23:23:28 current data : D
2019/08/21 23:23:28 v : [A B D]
2019/08/21 23:23:28 current data : F
2019/08/21 23:23:28 v : [A B F]
2019/08/21 23:23:28 current data : E
2019/08/21 23:23:28 v : [A B F E]
2019/08/21 23:23:28 current data : C
2019/08/21 23:23:28 v : [A C]
2019/08/21 23:23:28 current data : G
2019/08/21 23:23:28 v : [A C G]
2019/08/21 23:23:28 current data : H
2019/08/21 23:23:28 v : [A C G H]
2019/08/21 23:23:28 current data : I
2019/08/21 23:23:28 v : [A C I]
2019/08/21 23:23:28 []
```
**从输出结果来看,参数传递是值类型的,所以下层函数的改变无法影响到上级函数。但是slice不是引用类型的么。参数传递过程中理论上下层函数对其更改是可以影响到上层函数的吧**
有疑问加站长微信联系(非本文作者)