Leetcode Binary Tree Paths

复盘 :

go的字符串处理不熟悉 , 特殊情况没有一般化 , if else 特别多 , 看看bobo是怎么处理的,然后重写一版

pesudo code:

treePathsIn(node,rootPath)
    if node is leaf
        res[]=rootpath+node.val
        return

    else
        if node.left
            treePathsIn(node.left,rootpath+node.val)
        if node.right
            treePathsIn(node.right,rootpath+node.val)
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func binaryTreePaths(root *TreeNode) []string {
    if root==nil {
        return []string{}
    }

    s:=Solution{}
        if root.Left==nil && root.Right==nil {
        return []string{strconv.Itoa(root.Val)}
    }
    if root.Left!=nil {
        s.treePathsIn(root.Left,strconv.Itoa(root.Val))
    }
    if root.Right!=nil {
        s.treePathsIn(root.Right,strconv.Itoa(root.Val))
    }
    return s.res
}

type Solution struct {
    res []string
}

func (t *Solution) treePathsIn(node *TreeNode,rootPath string) {
    if node.Left==nil && node.Right==nil {
        t.res=append(t.res,rootPath+"->"+strconv.Itoa(node.Val))
        return
    } else {
        if node.Left!=nil {
            t.treePathsIn(node.Left,rootPath+"->"+strconv.Itoa(node.Val))
        }
        if node.Right!=nil {
            t.treePathsIn(node.Right,rootPath+"->"+strconv.Itoa(node.Val))
        }
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!