Skip to content

Commit 17758f5

Browse files
committed
solve(w11): 124. Binary Tree Maximum Path Sum
1 parent 4659042 commit 17758f5

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# https://leetcode.com/problems/binary-tree-maximum-path-sum/
2+
3+
from typing import Optional
4+
5+
# Definition for a binary tree node.
6+
class TreeNode:
7+
def __init__(self, val=0, left=None, right=None):
8+
self.val = val
9+
self.left = left
10+
self.right = right
11+
12+
class Solution:
13+
def maxPathSum(self, root: Optional[TreeNode]) -> int:
14+
"""
15+
[Complexity]
16+
- TC: O(n) (๊ฐ node๋ฅผ ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธ)
17+
- SC: O(height) (tree์˜ ๋†’์ด๋งŒํผ call stack)
18+
19+
[Approach]
20+
path์—๋Š” ๊ฐ™์€ node๊ฐ€ ๋‘ ๋ฒˆ ๋“ค์–ด๊ฐˆ ์ˆ˜ ์—†์œผ๋ฏ€๋กœ, ๊ฐ node ๋งˆ๋‹ค ํ•ด๋‹น node๋ฅผ ์ง€๋‚œ path์˜ max sum์€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.
21+
= (1) left child๋ฅผ ์ง€๋‚˜๋Š” path์˜ max_sum
22+
+ (2) right child๋ฅผ ์ง€๋‚˜๋Š” path์˜ max_sum
23+
+ (3) ํ˜„์žฌ node์˜ val
24+
๋”ฐ๋ผ์„œ ์ด๋Š” ์žฌ๊ท€ ๋ฌธ์ œ๋กœ ํ’€ ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๊ฐ ๋‹จ๊ณ„๋งˆ๋‹ค global max sum๊ณผ ๋น„๊ตํ•˜๋ฉฐ ๊ฐ’์„ ์—…๋ฐ์ดํŠธ ํ•˜๋ฉด ๋œ๋‹ค.
25+
26+
์ด๋•Œ node์˜ ๊ฐ’์€ ์Œ์ˆ˜๊ฐ€ ๋  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ, (1) & (2)๊ฐ€ ์Œ์ˆ˜๋ผ๋ฉด 0์œผ๋กœ ์ฒ˜๋ฆฌํ•ด์•ผ ํ•œ๋‹ค. ์ฆ‰,
27+
= (1) max(get_max_sum(node.left), 0)
28+
+ (2) max(get_max_sum(node.right), 0)
29+
+ (3) ํ˜„์žฌ node์˜ val
30+
๊ณผ ๊ฐ™์ด ๊ตฌํ•˜๊ณ , global max sum๊ณผ ์ด ๊ฐ’์„ ๋น„๊ตํ•˜๋ฉด ๋œ๋‹ค.
31+
32+
๋˜ํ•œ, ํ˜„์žฌ ๋ณด๊ณ  ์žˆ๋Š” node๊ฐ€ get_max_sum() ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์€
33+
= ํ˜„์žฌ node์˜ ๊ฐ’ + (1) & (2) ์ค‘ ํฐ ๊ฐ’
34+
์ด์–ด์•ผ ํ•œ๋‹ค. ์™œ๋ƒํ•˜๋ฉด ํ˜„์žฌ node๋ฅผ ๋‘ ๋ฒˆ ์ด์ƒ ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.
35+
"""
36+
37+
res = -1001
38+
39+
def get_max_sum(node):
40+
"""์ฃผ์–ด์ง„ node๊ฐ€ root์ธ tree์—์„œ, root๋ฅผ ์ง€๋‚˜๋Š” path์˜ max sum์„ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜"""
41+
nonlocal res
42+
43+
# base condition
44+
if not node:
45+
return 0
46+
47+
# compute left & right child's max path sum
48+
left_max_sum = max(get_max_sum(node.left), 0)
49+
right_max_sum = max(get_max_sum(node.right), 0)
50+
51+
# compute max path sum at this step
52+
max_sum = left_max_sum + right_max_sum + node.val
53+
54+
# update res
55+
res = max(res, max_sum)
56+
57+
return node.val + max(left_max_sum, right_max_sum)
58+
59+
get_max_sum(root)
60+
61+
return res

0 commit comments

Comments
ย (0)