給出一棵二叉樹(shù),尋找一條路徑使其路徑和最大,路徑可以在任一節(jié)點(diǎn)中開(kāi)始和結(jié)束(路徑和為兩個(gè)節(jié)點(diǎn)之間所在路徑上的節(jié)點(diǎn)權(quán)值之和)
樣例
給出一棵二叉樹(shù):
1
/ \
2 3
返回 6
代碼:
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if(null == root)
{
return 0;
}
subMaxPathSum(root);
return max;
}
public int subMaxPathSum(TreeNode node)
{
if(null == node)
{
return 0;
}
int leftMax = subMaxPathSum(node.left);
int rightMax = subMaxPathSum(node.right);
int subMax = Math.max(Math.max(Math.max(leftMax + node.val, rightMax + node.val), node.val),leftMax + rightMax + node.val);
if(max < subMax)
{
max = subMax;
}
return Math.max(Math.max(leftMax + node.val, rightMax + node.val), node.val);
}
}