337. House Robber III
Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 55% Topics: Dynamic Programming, Tree, Depth-First Search, Binary Tree
View full problem on LeetCode Reading material
Reference solution (spoiler · python)
# Time: O(n)
# Space: O(h)
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def robHelper(root):
if not root:
return (0, 0)
left, right = robHelper(root.left), robHelper(root.right)
return (root.val + left[1] + right[1], max(left) + max(right))
return max(robHelper(root))
Solution from kamyu104/LeetCode-Solutions · MIT
Similar questions