Original title URL: https://leetcode.com/problems/binary-tree-maximum-path-sum/
Given a binary tree and find the maximum path sum.
For this problem, a path are defined as any sequence of nodes from some starting node to any node into the tree along the par Ent-child connections. The path does not need to go through the root.
For example:
Given the below binary tree,
1
/\
2 3
Return 6.
Methods: Divide and conquer strategy, dynamic planning.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode (int x) {val = x;}
*/
public
class Solution {
// This is the
private int Max I rewrote myself according to the example on the Internet;
private int maxsidesum (TreeNode root) {
if (root = null) return 0;
int left = Maxsidesum (root.left);
int right = Maxsidesum (root.right);
int v = left + Root.val + right;
if (V > max) max = V;
int sum = root.val;
if (root.val+left>sum) sum = root.val+left;
if (root.val+right>sum) sum = root.val+right;
if (sum>max) max = sum;
return sum;
}
public int maxpathsum (TreeNode root) {
if (root = null) return 0;
max = Root.val;
Maxsidesum (root);
return max;
} This is the online search solution, very concise
// http://www.programcreek.com/2013/02/ leetcode-binary-tree-maximum-path-sum-java/
}
More concise version:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode (int x) {val = x;}
*
/Public
class Solution {
private int max = Integer.min_value;
private int Maxsidesum (TreeNode node) {
if (node = null) return 0;
int left = Maxsidesum (node.left);
int right = Maxsidesum (node.right);
max = Math.max (max, left + node.val + right);
Return Math.max (0, Node.val + math.max);
public int maxpathsum (TreeNode root) {
maxsidesum (root);
return max;
}