Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cf416c9

Browse files
二叉树相关 124题 二叉树中的最大路径和
1 parent 032bf43 commit cf416c9

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
def maxPathSum(root):
2+
"""
3+
:type root: TreeNode
4+
:rtype: int
5+
"""
6+
max_sum = -1001
7+
8+
def division(node, max_sum):
9+
current_max = node.val
10+
left_max_sum = -1001
11+
right_max_sum = -1001
12+
left_max_path = 0
13+
right_max_path = 0
14+
if node.left is not None:
15+
left_max_sum, left_max_path = division(node.left, max_sum)
16+
17+
if node.right is not None:
18+
right_max_sum, right_max_path = division(node.right, max_sum)
19+
20+
max_path = max(current_max, current_max + left_max_path, current_max + right_max_path)
21+
max_sum = max(max_sum, max_path, current_max + left_max_path + right_max_path, left_max_sum, right_max_sum)
22+
return max_sum, max_path
23+
24+
max_sum, max_path = division(root, max_sum)
25+
return max(max_sum, max_path)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /