MediumNo. 0337
House Robber III — LeetCode 337 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Dynamic Programming, Binary Tree
- Reading time
- 3 min
- Source
- leetcode.com
The problem
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.
Example
- Input
- root = [3,2,3,null,3,null,1]
- Output
- 7
- Explanation
- Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Python solution
# 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:
def dfs(root: Optional[TreeNode]) -> (int, int):
if root is None:
return 0, 0
la, lb = dfs(root.left)
ra, rb = dfs(root.right)
return root.val + lb + rb, max(la, lb) + max(ra, rb)
return max(dfs(root))Complexity
- Time
- O(n·m) (typical)
- Space · auxiliary
- O(n·m)or optimized
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 337. House Robber III is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0198 | House Robber | Medium |
| 0124 | Binary Tree Maximum Path Sum | Hard |
| 0968 | Binary Tree Cameras | Hard |
| 1372 | Longest ZigZag Path in a Binary Tree | Medium |
| 1373 | Maximum Sum BST in Binary Tree | Hard |
| 0095 | Unique Binary Search Trees II | Medium |
Frequently asked questions
- How hard is LeetCode 337. House Robber III?
LeetCode 337. House Robber III is rated Medium on LeetCode.
- What topics does LeetCode 337. House Robber III cover?
LeetCode 337. House Robber III is tagged Tree, Depth-First Search, Dynamic Programming and Binary Tree on LeetCode.