Skip to content

Commit 2df9595

Browse files
committed
update
1 parent 9072b09 commit 2df9595

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

46. 二叉树中的最大路径和.md

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
***路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中至多出现一次 。该路径至少包含一个 节点,且不一定经过根节点。***
2+
3+
Ref: https://leetcode.cn/problems/binary-tree-maximum-path-sum/solution/er-cha-shu-zhong-de-zui-da-lu-jing-he-by-leetcode-/
4+
![algo25](./images/algo25.jpg)
5+
6+
```
7+
输入:root = [-10,9,20,null,null,15,7]
8+
输出:42
9+
解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
10+
```
11+
12+
```
13+
# Definition for a binary tree node.
14+
# class TreeNode(object):
15+
# def __init__(self, val=0, left=None, right=None):
16+
# self.val = val
17+
# self.left = left
18+
# self.right = right
19+
class Solution(object):
20+
21+
#首先,考虑实现一个简化的函数 maxGain(node),该函数计算二叉树中的一个节点的最大贡献值,具体而言,就是在以该节点为根节点的子树中寻找以该节点为起点的一条路径,使得该路径上的节点值之和最大。
22+
#根据函数 maxGain 得到每个节点的最大贡献值之后,对于二叉树中的一个节点,该节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值,如果子节点的最大贡献值为正,则计入该节点的最大路径和,否则不计入该节点的最大路径和。
23+
def __init__(self):
24+
self.maxSum = float("-inf")
25+
26+
def maxPathSum(self, root: TreeNode) -> int:
27+
def maxGain(node):
28+
if not node:
29+
return 0
30+
31+
# 递归计算左右子节点的最大贡献值
32+
# 只有在最大贡献值大于 0 时,才会选取对应子节点
33+
leftGain = max(maxGain(node.left), 0)
34+
rightGain = max(maxGain(node.right), 0)
35+
36+
# 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值
37+
priceNewpath = node.val + leftGain + rightGain
38+
39+
# 更新答案
40+
self.maxSum = max(self.maxSum, priceNewpath)
41+
42+
# 返回节点的最大贡献值
43+
return node.val + max(leftGain, rightGain)
44+
45+
maxGain(root)
46+
return self.maxSum
47+
```

images/algo25.jpg

10.9 KB
Loading

0 commit comments

Comments
 (0)