题目
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
Return6.
思路
/*对于给定节点,以该节点为根的最大路径和:
* 1)左子树路径和+根值;
* 2)右子树路径和+根植;
* 3)根植;
* 4)左子树路径和+右子树路径和+根植;
* 取4者中的较大值
*
* 上述是对于某个节点来说,但是如果该节点上面还有父节点,计算父节点的最大路径和,
* 需要子路径最大和,所有还需要计算max(左子树路径和,右子树路径和)+根植
*
* ==》需要2个值:一个为子树最大路径和,一个为当前最大路径和;
* ==》一个为全局变量(不能作为递归函数的参数传递,int和Integer是传值,不是引用;);一个为返回值;
*/
实现
public int maxSumPath(Node node){
search(node);
return maxSum;
}
private int search(Node node) {
if(node==null){
return 0;
}
int left=Math.max(search(node.left),0);
int right=Math.max(search(node.right),0);
maxSum=Math.max(left+right+node.value,maxSum);
return Math.max(left, right)+node.value;
}