LeetCode 题解工作台

二叉树中的最大路径和

二叉树中的 路径 被定义为一条节点序列,序列中每对相邻节点之间都存在一条边。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。 路径和 是路径中各节点值的总和。 给你一个二叉树的根节点 root ,返回其 最大路径和 。 示例 1: 输入: root = […

category

4

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

困难 · 二分·树·traversal

bolt

答案摘要

我们思考二叉树递归问题的经典套路: 1. 终止条件(何时终止递归)

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

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

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

 

示例 1:

输入:root = [1,2,3]
输出:6
解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6

示例 2:

输入:root = [-10,9,20,null,null,15,7]
输出:42
解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42

 

提示:

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

解题思路

方法一:递归

我们思考二叉树递归问题的经典套路:

  1. 终止条件(何时终止递归)
  2. 递归处理左右子树
  3. 合并左右子树的计算结果

对于本题,我们设计一个函数 dfs(root)dfs(root),它返回以 rootroot 为根节点的二叉树的最大路径和。

函数 dfs(root)dfs(root) 的执行逻辑如下:

如果 rootroot 不存在,那么 dfs(root)dfs(root) 返回 00

否则,我们递归计算 rootroot 的左子树和右子树的最大路径和,分别记为 leftleftrightright。如果 leftleft 小于 00,那么我们将其置为 00,同理,如果 rightright 小于 00,那么我们将其置为 00

然后,我们用 root.val+left+rightroot.val + left + right 更新答案。最后,函数返回 root.val+max(left,right)root.val + \max(left, right)

在主函数中,我们调用 dfs(root)dfs(root),即可得到每个节点的最大路径和,其中的最大值即为答案。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是二叉树的节点数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxPathSum(self, root: Optional[TreeNode]) -> int:
        def dfs(root: Optional[TreeNode]) -> int:
            if root is None:
                return 0
            left = max(0, dfs(root.left))
            right = max(0, dfs(root.right))
            nonlocal ans
            ans = max(ans, root.val + left + right)
            return root.val + max(left, right)

        ans = -inf
        dfs(root)
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you account for negative node values when calculating the maximum path sum?

  • question_mark

    Can you explain how your DFS approach propagates maximum path contributions to the parent nodes?

  • question_mark

    Will you update the global maximum at each node correctly to include paths crossing through the node?

warning

常见陷阱

外企场景
  • error

    Forgetting to ignore negative subtree contributions when extending paths to parent nodes, leading to lower sums.

  • error

    Updating the global maximum only with single child contributions and missing paths through the current node.

  • error

    Confusing path extension to parent versus path sum including current node, which can incorrectly omit optimal paths.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find maximum path sum where path must start and end at leaf nodes only.

  • arrow_right_alt

    Compute the maximum sum path in a binary tree constrained to paths of length at most k edges.

  • arrow_right_alt

    Determine the maximum path sum in a binary tree when nodes can be revisited at most once.

help

常见问题

外企场景

二叉树中的最大路径和题解:二分·树·traversal | LeetCode #124 困难