Input: root = [1,2,3,null,5]
Output:
["1->2->5","1->3"]
Input: root = [1]
Output:
["1"]
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func binaryTreePaths(root *TreeNode) []string {
if root==nil { return nil }
ans := []string{}
recursive(root, strconv.Itoa(root.Val), &ans)
return ans
}
func recursive(root *TreeNode, str string, ans *[]string) {
if root.Left==nil && root.Right==nil {
*ans = append(*ans, str)
}
if root.Left!=nil {
recursive(root.Left, str+"->"+strconv.Itoa(root.Left.Val), ans)
}
if root.Right!=nil {
recursive(root.Right, str+"->"+strconv.Itoa(root.Right.Val), ans)
}
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func binaryTreePaths(root *TreeNode) []string {
if root==nil { return nil }
ans := []string{}
var recursive func(*TreeNode, string)
recursive = func(root *TreeNode, str string) {
if root.Left==nil && root.Right==nil {
ans = append(ans, str)
}
if root.Left!=nil {
recursive(root.Left, str+"->"+strconv.Itoa(root.Left.Val))
}
if root.Right!=nil {
recursive(root.Right, str+"->"+strconv.Itoa(root.Right.Val))
}
}
recursive(root, strconv.Itoa(root.Val))
return ans
}