LeetCode124——二叉树中的最大路径和

原题链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/description/

题目描述:

知识点:递归

思路:递归实现

递归函数的定义:求解包含root根节点的最大路径和。

递归终止条件

如果root为null,直接返回0。

递归过程

递归求解包含左孩子的以左孩子为根结点的最大路径和maxL,以及包含右孩子的以左孩子为根结点的最大路径和maxR。

如果maxL > 0,我们的当前的最大路径和就应该加上maxL。

如果maxR > 0,我们的当前的最大路径和就应该加上maxR。

扫描二维码关注公众号,回复: 5958781 查看本文章

最大路径和result取result和当前最大路径和的较大值。

该递归函数的返回结果应该是root的值,root的值加上maxL的值,root的值加上maxR的值,这三者间的较大值。

时间复杂度和空间复杂度均为O(h),其中h为树的高度。

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));
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32534441/article/details/89422497