Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created March 28, 2020 21:57
Show Gist options
  • Select an option

  • Save alldroll/b85b248b9f7570c9049c28c8cabe7986 to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/b85b248b9f7570c9049c28c8cabe7986 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/binary-tree-paths
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func binaryTreePaths(root *TreeNode) []string {
result := []string{}
findPaths(root, []int{}, &result)
return result
}
func findPaths(root *TreeNode, path []int, result *[]string) {
if root == nil {
return
}
if root.Left != nil {
findPaths(root.Left, append(path, root.Val), result)
}
if root.Left == nil && root.Right == nil {
*result = append(*result, stringifyPath(append(path, root.Val)))
return
}
if root.Right != nil {
findPaths(root.Right, append(path, root.Val), result)
}
}
func stringifyPath(path []int) string {
serialized := ""
for _, x := range path {
if len(serialized) == 0 {
serialized = fmt.Sprintf("%d", x)
} else {
serialized = fmt.Sprintf("%s->%d", serialized, x)
}
}
return serialized
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment