通过引用更改切片

时间:2017-11-09 07:18:17

标签: go

我有以下代码

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func binaryTreePaths(root *TreeNode) []string {
    paths := []string{}
    binaryTree(root, "", paths)
    return paths

}

func binaryTree(root *TreeNode, a string, paths []string) {

    if root == nil {
        return
    }

    if isLeaf(root) {
        paths = append(paths, a+strconv.Itoa(root.Val))
    }

    if root.Left != nil {
        binaryTree(root.Left, a+strconv.Itoa(root.Val)+"->", paths)
    }

    if root.Right != nil {
        binaryTree(root.Right, a+strconv.Itoa(root.Val)+"->", paths)
    }

}

func isLeaf(root *TreeNode) bool {

    if root == nil {
        return false
    }
    if root.Left == nil && root.Right == nil {
        return true
    }
    return false
}

我的问题是,在添加/弹出递归堆栈时,路径不会保留该值。但是当我使用地图时,即使在函数退出后,键/值也保持不变。如何在binaryTree完成后保留路径中的值?

即此代码打印出叶子的路径。给出以下树

/*           1
           /   \
          2     3
           \
            5
*/

答案应为{"1->2->5", "1->3"}

1 个答案:

答案 0 :(得分:3)

切片包含指向后备数组,长度和容量的指针。与Go中的所有其他类型一样,切片按值传递。

更改函数binaryTree以将切片返回给调用者。

func binaryTreePaths(root *TreeNode) []string {
    return binaryTree(root, "", nil)
}

func binaryTree(root *TreeNode, a string, paths []string) []string {

    if root == nil {
        return paths
    }

    if isLeaf(root) {
        paths = append(paths, a+strconv.Itoa(root.Val))
    }

    if root.Left != nil {
        paths =binaryTree(root.Left, a+strconv.Itoa(root.Val)+"->", paths)
    }

    if root.Right != nil {
        paths = binaryTree(root.Right, a+strconv.Itoa(root.Val)+"->", paths)
    }
    return paths
}

playground example