Path sum

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

复盘: 遗漏root节点为空的判断

效率不够高 , 如何优化?

Leetcode Path sum

pesudo code:

hasPathSum(node,sum)
    if node is leaf and node.val-sum=0
        return true

    elseif node is leaf and node.val-sum!=0
        return false

    else
        res1=false
        res2=false
        if node.left
             res1= hasPathSum(node.left,sum-node.val)
        if node.right
            res2=hasPathSum(node.right,sum-node.val)

        if res1||res2 
            return true
        else 
            return false


go implementation :

func hasPathSum(root *TreeNode, sum int) bool {
    return hasPathSumCustom(root, sum)
}

func hasPathSumCustom(node *TreeNode, sum int) bool {
    if node == nil {
        return false
    }
    if node.Left == nil && node.Right == nil && node.Val-sum == 0 {
        return true
    } else if node.Left == nil && node.Right == nil && node.Val-sum != 0 {
        return false
    } else {
        res1 := false
        res2 := false

        if node.Left != nil {
            res1 = hasPathSumCustom(node.Left, sum-node.Val)
        }
        if node.Right != nil {
            res2 = hasPathSumCustom(node.Right, sum-node.Val)
        }

        if res1 || res2 {
            return true
        } else {
            return false
        }
    }

}

相关文章

网友评论

    本文标题:Path sum

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