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 static int  ans = 0;
    public int maxMilkSum (TreeNode root) {
        // write code here
        if (root == null) {
            return 0;
        };
        search(root);
        return ans;
    }

    public static int search(TreeNode root){
        if(root==null) {
            return 0;
        }
        int left = search(root.left);
        int right = search(root.right);
        ans = Math.max(ans,left+right+root.val);
        return Math.max(left,right)+root.val;
    }

}

本题考察的知识点是二叉树的遍历,所用编程语言是java。

我们只要遍历将每个结点的最大左子树值和最大右子树值累加再加上根节点值进行比较,得出最大值