150强访谈

二叉树最大路径和

“二叉树最大路径和”问题的详细指南和 Python 实现。

问题陈述

二叉树中的路径是节点序列,其中序列中的每对相邻节点都有一条连接它们的边。一个节点最多只能在序列中出现一次。请注意,该路径不需要经过根。

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

给定二叉树的根,返回任何非空路径的最大路径和。

该树被表示为一个级别顺序列表。实现函数 maxPathSum(root: list) -> int

约束条件
  • The number of nodes in the tree is in the range [1, 30000]
  • -1000 <= Node.val <= 1000

示例

Example 1
Input
[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
[-10,9,20,None,None,15,7]
Output
42
Explanation

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

Example 3
Input
[-3]
Output
-3
Explanation

The only path is the single node -3.

Need a Hint?
考虑使用树特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。