算法篇:树之路径之和

算法:

算法采用递归,核心在于如何找到递归的终止条件,具体步骤如下:

1.采用递归的方式,sum的数值要随着遍历过的节点做递减操作,sum = sum-root.Val
2.递归的终止条件sum==0是其中之一,如果要求是叶子节点的也需要加上


题目1:

https://leetcode-cn.com/problems/path-sum/

代码实现:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func hasPathSum(root *TreeNode, sum int) bool {
    if root == nil {
         return false
    }
    // 叶子节点的判断,排除非叶子节点==sum的情况
    if root.Left == nil && root.Right == nil {
        return sum == root.Val
    }
    res := sum - root.Val 
    if hasPathSum(root.Left,res) {
        return true
    }
    if hasPathSum(root.Right,res) {
        return true
    }
    return false
}

执行结果:

题目2:

https://leetcode-cn.com/problems/path-sum-ii/

代码实现:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
var res [][]int
func pathSum(root *TreeNode, sum int) [][]int {
    res = [][]int{} // 为了清空 res 上次的数值
    if root == nil {
         return nil
    }
    // var res [][]int 
    var tmp []int
    dfs(root,sum,tmp)
    return res
}
func dfs(root *TreeNode, sum int, tmp []int) {
    if root == nil {
         return 
    }
    tmp = append(tmp,root.Val)
    if sum == root.Val && root.Left == nil && root.Right == nil {
        r := make([]int, len(tmp)) // 防止tmp对应的共享内容被修改
        copy(r, tmp)
        res = append(res, r)
        return 
    }
   
    dfs(root.Left,sum-root.Val,tmp)
    dfs(root.Right,sum-root.Val,tmp)
   
    return 
}

执行结果:

题目3:
https://leetcode-cn.com/problems/path-sum-iii/

代码实现:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func pathSum(root *TreeNode, sum int) int {
    if root == nil {
        return 0
    }
    result := countPath(root,sum)
    result += pathSum(root.Left,sum)
    result += pathSum(root.Right,sum)
    return result
}
func countPath(root *TreeNode, sum int) int {
    if root == nil {
         return 0
    }
    count := 0
    res := sum - root.Val
    if res == 0 {
        count = 1
    }
    return count + countPath(root.Left,res) + countPath(root.Right,res)
}
/*
以当前节点作为头结点的路径数量
以当前节点的左孩子作为头结点的路径数量
以当前节点的右孩子作为头结点的路径数量
*/

执行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值