|
| 1 | +from typing import Optional |
| 2 | +from unittest import TestCase, main |
| 3 | + |
| 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 | + |
| 13 | +class Solution: |
| 14 | + def maxPathSum(self, root: Optional[TreeNode]) -> int: |
| 15 | + return self.solve_dfs(root) |
| 16 | + |
| 17 | + """ |
| 18 | + Runtime: 11 ms (Beats 98.62%) |
| 19 | + Time Complexity: O(n) |
| 20 | + > dfs를 통해 모든 node를 방문하므로 O(n) |
| 21 | +
|
| 22 | + Memory: 22.10 MB (Beats 10.70%) |
| 23 | + Space Complexity: O(n) |
| 24 | + - dfs 재귀 호출 스택의 깊이는 이진트리가 최악으로 편향된 경우 O(n), upper bound |
| 25 | + - 나머지 변수는 O(1) |
| 26 | + > O(n), upper bound |
| 27 | + """ |
| 28 | + def solve_dfs(self, root: Optional[TreeNode]) -> int: |
| 29 | + max_path_sum = float('-inf') |
| 30 | + |
| 31 | + def dfs(node: Optional[TreeNode]) -> int: |
| 32 | + nonlocal max_path_sum |
| 33 | + |
| 34 | + if not node: |
| 35 | + return 0 |
| 36 | + |
| 37 | + max_left = max(dfs(node.left), 0) |
| 38 | + max_right = max(dfs(node.right), 0) |
| 39 | + max_path_sum = max(max_path_sum, node.val + max_left + max_right) |
| 40 | + |
| 41 | + return node.val + max(max_left, max_right) |
| 42 | + |
| 43 | + dfs(root) |
| 44 | + |
| 45 | + return max_path_sum |
| 46 | + |
| 47 | + |
| 48 | +class _LeetCodeTestCases(TestCase): |
| 49 | + def test_1(self): |
| 50 | + root = TreeNode(-10) |
| 51 | + node_1 = TreeNode(9) |
| 52 | + node_2 = TreeNode(20) |
| 53 | + node_3 = TreeNode(15) |
| 54 | + node_4 = TreeNode(7) |
| 55 | + node_2.left = node_3 |
| 56 | + node_2.right = node_4 |
| 57 | + root.left = node_1 |
| 58 | + root.right = node_2 |
| 59 | + |
| 60 | + # root = [-10, 9, 20, None, None, 15, 7] |
| 61 | + output = 42 |
| 62 | + |
| 63 | + self.assertEqual(Solution().maxPathSum(root), output) |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + main() |
0 commit comments