124. 二叉树中的最大路径和
深度优先搜索
class Solution {
/**
* 因为和有可能为负数,因此初始值取无穷小
*/
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxSum(root);
return max;
}
/**
* 在《104. 二叉树的最大深度》的基础上
* 顺便计算以root为起始节点的最大路径和
*/
public int maxSum(TreeNode root){
if (root == null){
return 0;
}
/**
* 分别计算左右子树的最大路径和
* 如果和小于0就取0
*/
int left = Math.max(maxSum(root.left), 0);
int right = Math.max(maxSum(root.right), 0);
/**
* 总的最大路径和就是左右之和加上root
*/
max = Math.max(left + right + root.val, max);
/**
* 返回的是以root为起始节点的最大路径和,取最大的子树加上root
*/
return Math.max(left, right) + root.val;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(logn)
*/
https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/