题解 | #牛的奶量统计II#
牛的奶量统计II
https://www.nowcoder.com/practice/9c56daaded6b4ba3a9f93ce885dab764?tpId=354&tqId=10591595&ru=/exam/oj/ta&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D354
知识点:
树的遍历
解题思路:
每遍历到一个节点,就将该节点作为初始节点往后进行路径和判断,如果中途路径和为target则返回true
语言:
Golang
package main import ( "fmt" ) /* * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 10, 2, 3, #, 4, 25, #, 6, 17, 8, 9, #, 1, 11, 12,#, 13, 14, #, 15 * @param root TreeNode类 * @param targetSum int整型 * @return bool布尔型 */ func hasPathSumII( root *TreeNode , targetSum int ) bool { // write code here if root == nil { return false } return pathSum(root, targetSum)||hasPathSumII(root.Left,targetSum)|| hasPathSumII(root.Right, targetSum) } func pathSum(root *TreeNode,targetSum int)bool{ if root == nil { return false } if root.Val == targetSum{ fmt.Println(root.Val) return true } return pathSum(root.Left, targetSum-root.Val)||pathSum(root.Right, targetSum-root.Val) }