forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathliza0525.py
More file actions
35 lines (30 loc) ยท 1.63 KB
/
Copy pathliza0525.py
File metadata and controls
35 lines (30 loc) ยท 1.63 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
34
35
# 7๊ธฐ ํ์ด
# ์๊ฐ ๋ณต์ก๋: O(n)
# - ํธ๋ฆฌ ์ ์ฒด๋ฅผ ํ์์ด๋ฏ๋ก ์ ์ฒด ๋
ธ๋ ๊ฐ์(n) ๋งํผ ์๊ฐ ์์
# ๊ณต๊ฐ ๋ณต์ก๋: O(h)
# - ํธ๋ฆฌ์ ๋์ด(h)๋งํผ ์ฌ๊ท ์คํ ์์
# - ์ต์
์ ๊ฒฝ์ฐ(ํธํฅ ํธ๋ฆฌ) O(n), ํ๊ท ์ ์ผ๋ก O(log n)
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self.res = root.val # ๊ฒฐ๊ณผ ๋ณ์๋ฅผ ํด๋์ค ๋ฉค๋ฒ ๋ณ์๋ก ์ง์
# ํ์ ํ์์ ์ด์ฉํด์ ๋ฌธ์ ๋ฅผ ํ๋ฉด ๋๋ค
def postorder(node):
if not node: # ๋
ธ๋๊ฐ None์ธ ๊ฒฝ์ฐ๋ 0์ ๋ฆฌํดํด์ค๋ค
return 0
# ์์ ๋
ธ๋๋ค ๊ฐ๊ฐ์ ์ต๋ํฉ์ ๋จผ์ ๊ณ์ฐํ๋ค.
# ์์๋ค์ ์ต๋ํฉ์ด ์์์ธ ๊ฒฝ์ฐ๋ ํ์ฌ ๋
ธ๋์ ์ต๋ํฉ ๊ณ์ฐ์ ๋ฐฉํด๊ฐ ๋๋ฏ๋ก
# 0๊ณผ ๋น๊ตํ์ฌ ๋ ํฐ ๊ฐ์ ์ ์ฅํ๋๋ก ํ๋ค
left_total = max(postorder(node.left), 0)
right_total = max(postorder(node.right), 0)
# ์ง๊ธ๊น์ง์ ์ต๋ํฉ(self.res)์ ์์ ๋
ธ๋ ๋ฐ ํ์ฌ ๋
ธ๋ val์ ํฉ์ ๋น๊ตํ์ฌ
# ๋ ํฐ ๊ฐ์ ์ง๊ธ๊น์ง์ ์ต๋ํฉ์ผ๋ก ์
๋ฐ์ดํธ ํ๋ค.
# - ํ์ฌ ๋
ธ๋๊ฐ root์ธ subtree์ ๊ฐ์ด ์ต๋์ผ ์ ์๊ธฐ ๋๋ฌธ์
self.res = max(
self.res,
left_total + right_total + node.val
)
# ์๋ก ์ฌ๋ฆด ๋๋ ์ผ์ชฝ ๋
ธ๋์ ์ค๋ฅธ์ชฝ ๋
ธ๋ ์ต๋ํฉ ์ค์
# ๋ ํฐ ๊ฐ์ ํ์ฌ ๋
ธ๋ value์ ๋ํด์ ์ฌ๋ ค์ค๋ค.
return max(left_total, right_total) + node.val
postorder(root)
return self.res