Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / 2 3
Return 6
.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { int max; /* getMax函数的意思是经过node节点的最大和。求最大和,有以下四种情况: 1. Node only (因为本题中的节点可能是负值!) 2. L-sub + Node 3. R-sub + Node 4. L-sub + Node + R-sub 求最大的结果,需要一个全局变量max,不断更新此变量 */ public int maxPathSum(TreeNode root) { max=Integer.MIN_VALUE; getMax(root); return max; } public int getMax(TreeNode node){ if(node==null) return 0; int left=getMax(node.left); int right=getMax(node.right); int resMax=node.val; if(left>0) resMax+=left; if(right>0) resMax+=right; max=Math.max(max,resMax); return Math.max(node.val,Math.max(left+node.val,right+node.val)); } }