257. Binary Tree Paths
Easy
108579FavoriteShare
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func binaryTreePaths(root *TreeNode) []string {
ans:=[]string{}
if root==nil{
return ans
}
s:=""
s+=strconv.Itoa(root.Val)
help(root,&ans,s)
return ans
}
func help(root *TreeNode,ans *[]string,temp string){
if root.Left!=nil{
l:=temp+"->"+strconv.Itoa(root.Left.Val)
help(root.Left,ans,l)
}else{
if root.Right==nil{
*ans=append(*ans,temp)
}
}
if root.Right!=nil{
r:=temp+"->"+strconv.Itoa(root.Right.Val)
help(root.Right,ans,r)
}
}