- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinary_tree_maximum_path_sum.py
More file actions
Latest commit
33 lines (28 loc) · 1.24 KB
/
Copy pathbinary_tree_maximum_path_sum.py
File metadata and controls
33 lines (28 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
importunittest
from .binary_treeimportTreeNode
classSolution(unittest.TestCase):
deftest(self):
TEST_CASES= [
("1(2)(3)", 6),
]
fortree, max_path_suminTEST_CASES:
self.assertEqual(max_path_sum, self.max_path_sum(TreeNode.from_str(tree)))
defmax_path_sum(self, root: TreeNode) ->int:
# 这就是Python除了for/while语句内部变量能在while外面使用之外
# 又一个虽然方便但是不严谨的地方,示例遍历可以随时定义
self.max_path=float('-inf')
# 后序遍历寻找路径
deffind_max(node: TreeNode) ->int:
# nonlocal max_path
ifnodeisNone:
return0
# 只有当左右子树贡献值大于0时才会被选中
left=max(find_max(node.left), 0)
right=max(find_max(node.right), 0)
# 先判断当前左-中-右路径是不是最长的
self.max_path=max(self.max_path, left+node.val+right)
# 由于往上的路径只能是从左往上或从右往上,所以选一个最大的
returnnode.val+max(left, right)
find_max(root)
# noinspection PyTypeChecker
returnself.max_path