题解 | #农场最大产奶牛群#
农场最大产奶牛群
https://www.nowcoder.com/practice/16d827f124e14e05b988f3002e7cd651?tpId=354&tqId=10591611&ru=/exam/oj/ta&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D354
解题思路:
遍历二叉树,一边遍历边返回当前最大的路径和,同时计算当前节点为根的树的res
语言:
Golang
package main /* * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ func maxMilkSum( root *TreeNode ) int { if root == nil{ return 0 } res:=0 var maxSum func(root *TreeNode)int maxSum = func(root *TreeNode)int{ if root == nil{ return 0 } left:=maxSum(root.Left) right:=maxSum(root.Right) res=max(res,root.Val+left+right) return root.Val+max(maxSum(root.Left),maxSum(root.Right)) } maxSum(root) return res } func max(a,b int)int{ if a>b { return a } return b }