|
| 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