Question 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,
Vc + release/release + release/PX08r3wre + release/release + trXEtqjS5crHw7 + release/ajrMq + wP22/release = "http://www.2cto.com/uploadfile/Collfiles/20140511/20140511092309181.png" alt = "\">
Take node 2 as an example. The value returned to the root node 1 should be 2 + 5 = 7, instead of 2 + 4 + 5 = 11, because 2 can only access
AC code
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { private static int maxValue; public static int maxPathSum(TreeNode root) { maxValue = root == null ? 0 : root.val; findPath(root); return maxValue; } public static int findPath(TreeNode root) { if (root == null) { return 0; } int left = Math.max(findPath(root.left), 0); int right = Math.max(findPath(root.right), 0); maxValue = Math.max(maxValue, root.val + left + right); int current = Math.max(root.val, Math.max(root.val + left, root.val + right)); return current; }}