-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_337.py
More file actions
39 lines (29 loc) · 962 Bytes
/
task_337.py
File metadata and controls
39 lines (29 loc) · 962 Bytes
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
from typing import Optional
from functools import cache
# 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
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
ans = 0
@cache
def go(u):
if u == None:
return 0
if u.left == None and u.right == None:
return u.val
x = go(u.left) + go(u.right)
y = u.val
if u.left != None:
y += go(u.left.left) + go(u.left.right)
if u.right != None:
y += go(u.right.left) + go(u.right.right)
nonlocal ans
ans = max(ans, x, y)
return max(x, y)
ans = root.val
go(root)
return ans