Binary Tree Paths

作者: carlclone | 来源:发表于2019-07-02 13:27 被阅读0次

    复盘 :

    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))
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:Binary Tree Paths

        本文链接:https://www.haomeiwen.com/subject/puezcctx.html