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"}