House Robber III LeetCode solution in Python

1
class Solution:
2
def rob(self, root: Optional[TreeNode]) -> int:
3
hashMap = {}
4

5
def helper(root: Optional[TreeNode]) -> int:
6
if not root:
7
return 0
8
if root in hashMap:
9
return hashMap[root]
10
ansOption1 = root.val
11
if root.left is not None:
12
ansOption1 += helper(root.left.left) + helper(root.left.right)
13
if root.right is not None:
14
ansOption1 += helper(root.right.left) + helper(root.right.right)
15
ansOption2 = helper(root.left) + helper(root.right)
16
ansFinal = max(ansOption1, ansOption2)
17
hashMap[root] = ansFinal
18
return ansFinal
19

20
return helper(root)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0