题解 | #牛群特殊路径的数量#
牛群特殊路径的数量
https://www.nowcoder.com/practice/1c0f95d8396a432db07945d8fe51a4f5?tpId=354&tqId=10595825&ru=/exam/company&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Fcompany
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param sum int整型
* @return int整型
*/
func pathSum( root *TreeNode , sum int ) int {
// write code here
var ans int
var check func(*TreeNode,int)int
check=func(root *TreeNode,target int) int {
if root==nil{
return 0
}
if target-root.Val==0{
return 1
}
if target-root.Val<0{
return 0
}
return check(root.Left,target-root.Val)+check(root.Right,target-root.Val)
}
var dfs func(*TreeNode)
dfs=func(root *TreeNode) {
if root==nil{
return
}
ans+=check(root, sum)
dfs(root.Left)
dfs(root.Right)
}
dfs(root)
return ans
}
查看20道真题和解析