forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoh6077.py
More file actions
48 lines (45 loc) ยท 1.69 KB
/
doh6077.py
File metadata and controls
48 lines (45 loc) ยท 1.69 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
36
37
38
39
40
41
42
43
44
45
46
47
48
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
# # Initially thought I need to use BFS ( misunderstood the question)
# if not root:
# return
# queue = deque([root])
# result = []
# val = 0
# max_sum = float('-inf')
# while queue:
# currentNode = queue.popleft()
# result.append(currentNode.val)
# val += currentNode.val
# if currentNode.left:
# queue.append(currentNode.left)
# val += currentNode.left.val
# if currentNode.right:
# queue.append(currentNode.right)
# val += currentNode.right.val
# max_sum = max(val, max_sum)
# val = 0
# return max_sum
res = [root.val]
def dfs(root):
if not root:
return 0
leftMax = dfs(root.left)
rightMax = dfs(root.right)
# ์์ ๊ฐ์ด ์์์ผ๊ฒฝ์ฐ 0์ผ๋ก ์ฒ๋ฆฌ
leftMax = max(leftMax, 0)
rightMax = max(rightMax, 0)
# "์ง๊ธ๊น์ง ๋ฐ๊ฒฌํ ๊ฒฝ๋ก ์ค ์ต๊ณ ์ ํฉ"์ res[0]์ ์ ์ฅ
# Job 1: ๋๋ฅผ ๊บพ์์ (Anchor)์ผ๋ก ํ๋ '์์นํ' ๊ฒฝ๋ก ๊ณ์ฐ
res[0] = max(res[0], root.val + leftMax + rightMax)
# Job 2: ๋ถ๋ชจ์๊ฒ ์ฌ๋ฆด '์ง์ ' ๊ฒฝ๋ก ๋ฆฌํด
return root.val + max(leftMax, rightMax)
dfs(root)
return res[0]