原题链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/description/
题目描述:
知识点:递归
思路:递归实现
递归函数的定义:求解包含root根节点的最大路径和。
递归终止条件:
如果root为null,直接返回0。
递归过程:
递归求解包含左孩子的以左孩子为根结点的最大路径和maxL,以及包含右孩子的以左孩子为根结点的最大路径和maxR。
如果maxL > 0,我们的当前的最大路径和就应该加上maxL。
如果maxR > 0,我们的当前的最大路径和就应该加上maxR。
最大路径和result取result和当前最大路径和的较大值。
该递归函数的返回结果应该是root的值,root的值加上maxL的值,root的值加上maxR的值,这三者间的较大值。
时间复杂度和空间复杂度均为O(h),其中h为树的高度。
result用于记录每一个顶点可以的最大和,这些值的最大值即为所求。
return Math.max(root.val, Math.max(root.val + maxL, root.val + maxR));
返回值之所以是这三个的最大值是因为,需要返回给上一级,且需要时可以走的路,即必须走root,故root.left与root.right最多只能走一个。
JAVA代码:
public class Solution {
int result = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxSum(root);
return result;
}
private int maxSum(TreeNode root){ //求包含root根节点的最大路径和
if(null == root){
return 0;
}
int data = root.val;
int maxL = maxSum(root.left);
if(maxL > 0){
data += maxL;
}
int maxR = maxSum(root.right);
if(maxR > 0){
data += maxR;
}
result = Math.max(result, data); //记录当前树的最大路径和
return Math.max(root.val, Math.max(root.val + maxL, root.val + maxR));
}
}