题目
路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 root ,返回其 最大路径和 。
- 来源:力扣(LeetCode)
- 链接:leetcode.cn/problems/bi…
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一
思路
- 深度优先遍历。
- 返回的数据,需要是
root.val + max(left, right)
。但是答案需要是max(root.val + left + right, root.val+max(left, right))
- 答案需要是全局的
代码
class Solution {
private int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
helper(root);
return max;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int left = Math.max(0, helper(root.left));
int right = Math.max(0, helper(root.right));
int sum = root.val + Math.max(left, right);
max = Math.max(max, Math.max(root.val + left + right, sum));
return sum;
}
}
update20220525
private int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
helper(root);
return max;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int left = helper(root.left);
int right = helper(root.right);
int temp = Math.max(left, right);
max = Math.max(max, Math.max(root.val, Math.max(root.val + left + right, root.val + temp)));
return Math.max(root.val, root.val + temp);
}
复杂度
- 时间复杂度:O(n)
- 空间复杂度:O(n)