温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

c++路径之和实例分析

发布时间:2022-03-17 16:06:50 来源:亿速云 阅读:123 作者:iii 栏目:大数据

本文小编为大家详细介绍“c++路径之和实例分析”,内容详细,步骤清晰,细节处理妥当,希望这篇“c++路径之和实例分析”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

算法:

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

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

题目1:路径总和

代码实现:

/** * 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:路径总和2

代码实现:

/** * Definition for a binary tree node. * type TreeNode struct { *     Val int *     Left *TreeNode *     Right *TreeNode * } */var res [][]intfunc 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:路径总和3

代码实现:

/** * 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)}/*以当前节点作为头结点的路径数量以当前节点的左孩子作为头结点的路径数量以当前节点的右孩子作为头结点的路径数量*/

读到这里,这篇“c++路径之和实例分析”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI