摘抄自:https://segmentfault.com/a/1190000003554858#articleHeader2node
题目:segmentfault
Given a binary tree, find the maximum path sum.spa
The path may start and end at any node in the tree.code
For example: Given the below binary tree,blog
1 / \ 2 3
Return 6.递归
思路:首先咱们分析一下对于指定某个节点为根时,最大的路径和有多是哪些状况。第一种是左子树的路径加上当前节点,第二种是右子树的路径加上当前节点,第三种是左右子树的路径加上当前节点(至关于一条横跨当前节点的路径),第四种是只有本身的路径。乍一看彷佛以此为条件进行自下而上递归就好了,然而这四种状况只是用来计算以当前节点根的最大路径,若是当前节点上面还有节点,那它的父节点是不能累加第三种状况的。因此咱们要计算两个最大值,一个是当前节点下最大路径和,另外一个是若是要链接父节点时最大的路径和。咱们用前者更新全局最大量,用后者返回递归值就好了。get
Java代码:io
public class Solution { private int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { helper(root); return max; } public int helper(TreeNode root) { if(root == null) return 0; int left = helper(root.left); int right = helper(root.right); //链接父节点的最大路径是1、2、四这三种状况的最大值 int currSum = Math.max(Math.max(left + root.val, right + root.val), root.val); //当前节点的最大路径是1、2、3、四这四种状况的最大值 int currMax = Math.max(currSum, left + right + root.val); //用当前最大来更新全局最大 max = Math.max(currMax, max); return currSum; } }