0

I have the following code

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
}

My issue is that paths doesn't keep the value when the recursion stack is added/popped. But when I use maps that keys/values stay the same even after the function exits. How do I keep the values in paths after binaryTree finishes?

i.e This code prints out paths to leaves. Given the following tree

/*           1
           /   \
          2     3
           \
            5
*/

Answer should be {"1->2->5", "1->3"}

martinap
  • 37
  • 1
  • 9

1 Answers1

2

A slice contains a pointer to a backing array, length and capacity. Like all other types in Go, slices are passed by value.

Change the function binaryTree to return the slice to the caller.

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

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242