For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
For example: Given the below binary tree,
1
/ \
2 3
Return 6.
Solution
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassSolution {publicintmaxPathSum(TreeNode root) {if (root ==null) return0;Result result =maxPathHelper(root);returnresult.maxPath; }privateResultmaxPathHelper(TreeNode root) {if (root ==null) {returnnewResult(Integer.MIN_VALUE,0); }Result left =maxPathHelper(root.left);Result right =maxPathHelper(root.right);// left.maxPath, right.maxPath, left.rootPath + right.rootPath+root.val// left.rootPath + root.val, right.rootPath+root.val, root.val, 0int tmep =left.rootPath+right.rootPath+root.val;int maxPath =Math.max(Math.max(left.maxPath,right.maxPath), tmep);int rootPath =Math.max(Math.max(Math.max(left.rootPath+root.val,right.rootPath+root.val),root.val),0);returnnewResult(maxPath, rootPath); }privateclassResult {int maxPath;int rootPath;publicResult(int max,int rootPath) {this.maxPath= max;this.rootPath= rootPath; } }}