题解 | #农场最大产奶牛群#
农场最大产奶牛群
https://www.nowcoder.com/practice/16d827f124e14e05b988f3002e7cd651
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ public int maxMilkSum (TreeNode root) { // write code here this.maxSum = Integer.MIN_VALUE; maxPathSum(root); return maxSum; } private int maxSum; private int maxPathSum(TreeNode root) { if (root == null) return 0; int leftMax = Math.max(maxPathSum(root.left), 0); int rightMax = Math.max(maxPathSum(root.right), 0); maxSum = Math.max(maxSum, root.val + leftMax + rightMax); return root.val + Math.max(leftMax, rightMax); } }
- 定义一个成员变量 maxSum,用于计算最大路径和
- 最大路径和 = 根节点值 + 左子树最大路径和 + 右子树最大路径和
- 基于递归,每次分别递归左右子树求解:左子树最大路径和、右子树最大路径和
线性表基础 文章被收录于专栏
链表、递归、栈