leetcode困难124二叉树中的最大路径和

Posted qq_40707462

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode困难124二叉树中的最大路径和相关的知识,希望对你有一定的参考价值。



思路:考虑一棵树,中+左+右 三个部分,

  1. 同时经过左右子树,即当前的 root 就是起点,不再向上累加
  2. 左右子树只选择其中一条路,那选中的子树连同root一起向上累加
  3. 如果出现负数,可以置零表示不选择当前子树,左右子树都为0那只算root就行了

时间复杂度:O(N),对每个节点访问不超过 2 次。
空间复杂度:O(N),空间复杂度主要取决于递归调用层数,最大层数等于二叉树的高度,最坏情况下,二叉树的高度等于二叉树中的节点个数。

class Solution 
    int res=Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) 
        dfs(root);
        return res;
    
    public int dfs(TreeNode root)
        if(root==null) return 0;
        int left=Math.max(0,dfs(root.left));//如果和为负则应当置0表示不经过该子树(root还是会算的)
        int right=Math.max(0,dfs(root.right));
        res=Math.max(res,root.val+left+right);//root为起点,连同左右,为一条路
        return Math.max(left,right)+root.val;//返回值,左右只能选一条路,向上累加
    

以上是关于leetcode困难124二叉树中的最大路径和的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 124. 二叉树中的最大路径和

leetcode——124. 二叉树中的最大路径和

124. 二叉树中的最大路径和

LeetCode 124. 二叉树中的最大路径和 | Python

Leetcode 124.二叉树中的最大路径和

[LeetCode] 124. 二叉树中的最大路径和