原题网址:https://leetcode.com/problems/binary-tree-maximum-path-sum/
Given a binary tree, find the maximum path sum.
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 does not need to go through the root.
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 {
// 这是我根据网上的例子,自己重写的
private int max;
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;
}
// 这是网上搜索的解决方案,非常简洁
// http://www.programcreek.com/2013/02/leetcode-binary-tree-maximum-path-sum-java/
}
更简洁的版本:
/**
* 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(left, right));
}
public int maxPathSum(TreeNode root) {
maxSideSum(root);
return max;
}
}