跳至主要內容

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


124. 二叉树中的最大路径和open in new window

🔴   🔖  深度优先搜索 动态规划 二叉树  🔗 LeetCodeopen in new window

题目

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node's values in the path.

Given the root of a binary tree, return the maximum path sum of any non-empty path.

Example 1:

Input: root = [1,2,3]

Output: 6

Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

Example 2:

Input: root = [-10,9,20,null,null,15,7]

Output: 42

Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.

Constraints:

  • The number of nodes in the tree is in the range [1, 3 * 10^4].
  • -1000 <= Node.val <= 1000

题目大意

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

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

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

解题思路

给定一个二叉树,路径不一定要从根节点出发,可以从任意节点开始,并可以到达任意节点。要找到路径和的最大值,需要递归地计算每个节点的最大贡献值。

  • 对于当前节点 root,定义一个函数 maxGain(node),表示从当前节点出发到任意下属节点的路径最大贡献值。贡献值是指该节点及其子树为路径提供的最大和。
  • 当递归到叶节点的 null 节点时,返回 0,表示空节点的贡献为 0
  • 计算出当前节点左右子树的最大贡献值 leftGainrightGain
  • 当前节点的最大路径和可以是:
    • 当前节点值 node.val
    • 当前节点 + 左子树的贡献。
    • 当前节点 + 右子树的贡献。
    • 当前节点 + 左子树的贡献 + 右子树的贡献(代表路径穿过当前节点)。
  • 更新全局最大路径和 res
  • 返回当前节点可以提供给父节点的最大路径贡献,值为 node.val + max(leftGain, rightGain),即选择左右子树中贡献较大的那个。

复杂度分析

  • 时间复杂度O(n),其中 n 是二叉树中的节点数量。我们需要遍历每个节点一次。
  • 空间复杂度O(h),其中 h是二叉树的高度。递归栈的深度取决于树的高度,在最坏情况下,树的高度为O(n),即退化成链表的情况。

代码

/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxPathSum = function (root) {
	let res = -Infinity;

	const maxGain = (node) => {
		if (!node) return 0;

		// 递归计算左右子树的最大贡献值
		let leftGain = Math.max(maxGain(node.left), 0); // 负数时选择0
		let rightGain = Math.max(maxGain(node.right), 0);

		// 更新全局最大路径和
		res = Math.max(res, node.val + leftGain + rightGain);

		// 返回当前节点可以提供给父节点的最大贡献
		return node.val + Math.max(leftGain, rightGain);
	};

	maxGain(root);

	return res;
};

相关题目

题号标题题解标签难度
112路径总和open in new window[✓]open in new window 深度优先搜索 广度优先搜索 1+
129求根节点到叶节点数字之和open in new window[✓]open in new window 深度优先搜索 二叉树
666路径总和 IVopen in new window 深度优先搜索 数组 2+
687最长同值路径open in new window 深度优先搜索 二叉树
1376通知所有员工所需的时间open in new window 深度优先搜索 广度优先搜索
2538最大价值和与最小价值和的差值open in new window 深度优先搜索 数组 1+