题解 | #农场最大产奶牛群#
农场最大产奶牛群
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整型
*/
int maxPath = Integer.MIN_VALUE;
public int maxMilkSum (TreeNode root) {
// write code here
if(root==null) return 0;
dfs(root);
return maxPath; //返回最大路径和
}
public int dfs(TreeNode root){
if(root==null) return 0;
int left = dfs(root.left);
int right = dfs(root.right);
maxPath = Math.max(maxPath, left+right+root.val);
return Math.max(left,right)+root.val; //返回最大路径和
}
}

