题解 | #二叉树中和为某一值的路径(三)#

二叉树中和为某一值的路径(三)

https://www.nowcoder.com/practice/965fef32cae14a17a8e86c76ffe3131f

package main

import . "nc_tools"

/*
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param root TreeNode类
 * @param sum int整型
 * @return int整型
 */
func FindPath(root *TreeNode, sum int) int {
	if root == nil {
		return 0
	}
	tempCount := 0
	if sum-root.Val == 0 {
		tempCount= tempCount+1
	}
    if root.Left!=nil{
	   tempCount = tempCount+ FindPath(root.Left, sum)
       tempCount = tempCount+ dfs(root.Left, sum-root.Val) 
	}
	if root.Right!=nil{
		tempCount = tempCount+ FindPath(root.Right, sum)
		tempCount = tempCount+ dfs(root.Right, sum-root.Val) 
	}
	return tempCount
}


func dfs(root *TreeNode, sum int) int{
	if root == nil {
		return 0
	}
	tempCount := 0
	if sum== root.Val {
		tempCount= tempCount+1
	}
    if root.Left!=nil{
       tempCount = tempCount+ dfs(root.Left, sum-root.Val) 
	}
	if root.Right!=nil{
		tempCount = tempCount+ dfs(root.Right, sum-root.Val) 
	}
	return tempCount
}


需要注意从每一个子节点开始的时候,总数需要不变,总数变的话直接走子函数就行了

全部评论

相关推荐

07-11 22:27
中南大学 Java
程序员牛肉:学历的话没问题。但是没问题的也就只有学历了。 其实你的整体架构是正确的,博客接着干。但是项目有点过于简单了。从后端的角度上讲,你这也就是刚入门的水平,所以肯定约面试够呛。 如果你要应聘后端岗位,那你第一个项目竟然是仿写操作系统。这个你要面试官咋问你。你一定要记住一点,你简历上写的所有的东西,都是为了证明你有能力胜任当前的岗位,而不是为了证明你自己会什么。 如果你只是浅浅的做几个项目,描述也都是烂大街。技术点也都是各种混水类的配置类需求,那你就不要幻想自己能走多远。一定要保持思考,保持学习。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务