Golang recursive solution 3ms


  • 0
    M

    Propably it can be optimized with the convention not call it with a nil parameter. In that case you can specifiy the recursive calls for nodes with just one child too.

    func binaryTreePaths(root *TreeNode) []string {
        if(root==nil){
            return []string{}
        }    
        val:=strconv.Itoa(root.Val)
        if(root.Left==nil && root.Right==nil){
            return []string{val}
        }
        str:=[]string{}
        for _, value := range append(binaryTreePaths(root.Left),binaryTreePaths(root.Right)...){
            str= append(str,val+"->"+value)
        }
        return str
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.