美文网首页LeetCode By Go
[LeetCode By Go 105]112. Path Su

[LeetCode By Go 105]112. Path Su

作者: miltonsun | 来源:发表于2017-09-11 17:01 被阅读30次

    题目

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

    For example:
    Given the below binary tree and sum = 22,

                 5
                / \
               4   8
              /   / \
             11  13  4
            /  \      \
           7    2      1
    

    return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

    解题思路

    判断从根节点到叶子节点的路径节点和是否等于目标值

    1. 定义全局变量hasSum用于记录是否有从根节点到叶子节点的路径节点和等于目标值
    2. 遍历所有root-to-leaf path,累加得到各路径的值,
    3. 如果和等于目标值,则将全局变量hasSum置为true
    4. 最后返回hasSum的值

    注意
    需要判断叶子节点,叶子节点的左右节点都为空

    代码

    /**
     * Definition for a binary tree node.
     * type TreeNode struct {
     *     Val int
     *     Left *TreeNode
     *     Right *TreeNode
     * }
     */
    
    var hasSum bool
    
    func addPathSum(t *TreeNode, sum, sumNow int)  {
        if t == nil {
            return
        } 
        
        val := t.Val
        sumNow += val
        if sum == sumNow && isLeaf(t){
                hasSum = true
        } else {
            addPathSum(t.Left, sum, sumNow)
            addPathSum(t.Right, sum, sumNow)
        }
    }
    
    func isLeaf(t *TreeNode) bool {
        if t != nil && t.Left ==nil && t.Right == nil {
            return true
        }   
        return false
    }
    
    func hasPathSum(root *TreeNode, sum int) bool {
        hasSum = false
        if root == nil {
            return false
        }
    
        sumNow := root.Val
        if isLeaf(root) && sum == sumNow {
            hasSum = true
        }
        
        addPathSum(root.Left, sum, sumNow)
        addPathSum(root.Right, sum, sumNow)
    
            return hasSum
    }
    

    相关文章

      网友评论

      • 622364ec1cf9:if hasSum {
        return true
        } else {
        return false
        }
        可以改成return hasSum,哈哈哈,小瑕疵,还有isLeaf函数
        miltonsun::smile: 是的,多此一举了:pray:

      本文标题:[LeetCode By Go 105]112. Path Su

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