Binary Tree Maximum Path Sum
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,
1 / \ 2 3
Return 6
.
题解:本题可以通过递归的方式来求解,以某节点为根的路径和为左子树的和加右子树的和,再加上该节点的值;有关树的很多题目都可以通过递归的方式来求解,因为树本身就是一个递归的结构。代码如下:
public class Solution {
private int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
pathSum(root);
return max;
}
public int pathSum(TreeNode root){
if(root == null){
return Integer.MIN_VALUE;
}
int left = Math.max(pathSum(root.left), 0);
int right = Math.max(pathSum(root.right), 0);
int sum = root.val + left + right;
if(sum > max)
max = sum;
return (left > right) ? (left+root.val) : (right+root.val);
}
}