跳到主要内容

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

题目描述

二叉树中的 路径 被定义为一条节点序列,序列中每对相邻节点之间都存在一条边。 同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ,返回其 最大路径和

示例 1:

示例 1

输入root = [1,2,3]

输出6

解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6

示例 2:

示例 2

输入root = [-10,9,20,null,null,15,7]

输出42

解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42

提示:

  • 树中节点数目范围是 [1, 3 * 10^4]
  • -1000 <= Node.val <= 1000

出处LeetCode

解法一:递归

思路

可以递归地计算以每个节点为根的子树的最大路径和,然后更新最大路径和。

实现

function maxPathSum(root: TreeNode | null): number {
let maxSum = Number.MIN_SAFE_INTEGER;
const maxGain = (node: TreeNode | null): number => {
if (node === null) return 0;
const leftGain = Math.max(maxGain(node.left), 0);
const rightGain = Math.max(maxGain(node.right), 0);
const priceNewPath = node.val + leftGain + rightGain;
maxSum = Math.max(maxSum, priceNewPath);
return node.val + Math.max(leftGain, rightGain);
};
maxGain(root);
return maxSum;
}

复杂度分析

  • 时间复杂度:O(n)O(n),其中 nn 是二叉树中的节点个数。
  • 空间复杂度:O(h)O(h),其中 hh 是二叉树的高度。