larscheng / algo

0 stars 0 forks source link

【Check 58】2024-04-22 - 124. 二叉树中的最大路径和 #160

Open larscheng opened 2 months ago

larscheng commented 2 months ago

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

larscheng commented 2 months ago

思路

class Solution { //递归计算每个节点的最大贡献值,根节点的最大贡献值=root.val+Max(left,right) //递归过程中记录最大的路径和 //O(n)/O(n) int res = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { maxGain(root); return res; }

private int maxGain(TreeNode root) {
    if (root == null) {
        return 0;
    }

    int leftValue = Math.max(maxGain(root.left), 0);
    int rightValue = Math.max(maxGain(root.right), 0);

    int totalValue = root.val + leftValue + rightValue;
    res = Math.max(totalValue, res);

    return root.val + Math.max(leftValue, rightValue);
}

}



### 复杂度
- 时间复杂度:O(n)
- 空间复杂度:O(n)