124. Binary Tree Maximum Path Sum

xiaoxiao2021-02-28  125

1.定义maxDeep(x)为以x为根节点的树的max path

   maxDeep(x)等于在下面a,b,c中找到一个最大的值,c的话是因为左子树的max path 和 右子树的max path可能值为负

   a.左子树的max path  + x自身的值

   b.右子树的max path  + x自身的值

   c.x自身的值

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { int ans = Integer.MIN_VALUE; int maxDeep(TreeNode root){ if(root == null) return 0; int curAns = root.val; int lMax = maxDeep(root.left); int rMax = maxDeep(root.right); if(lMax > 0 ){ curAns += lMax; } if(rMax >0){ curAns += rMax; } if(curAns > ans){ ans = curAns; } return Math.max(root.val,Math.max(root.val+lMax,root.val+rMax)); } public int maxPathSum(TreeNode root) { maxDeep(root); return ans; } }

转载请注明原文地址: https://www.6miu.com/read-80405.html

最新回复(0)