#337

House Robber III

Medium
Dynamic ProgrammingTreeDepth-First SearchBinary TreeDynamic ProgrammingTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(h)
💡

Intuition

Time O(n)Space O(h)

The optimal approach uses dynamic programming to store results of subproblems, avoiding redundant calculations. By using a helper function that returns two values (maximum money if robbed and if not robbed), we can efficiently compute the result in a single traversal of the tree.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a helper function that returns two values: max money if the current node is robbed and if it is not robbed.
  2. 2Step 2: For each node, calculate the maximum money by considering both scenarios (robbing and not robbing).
  3. 3Step 3: Store results in a tuple and return the maximum of the two values.
solution.py17 lines
1class TreeNode:
2    def __init__(self, val=0, left=None, right=None):
3        self.val = val
4        self.left = left
5        self.right = right
6
7class Solution:
8    def rob(self, root: TreeNode) -> int:
9        def dfs(node):
10            if not node:
11                return (0, 0)
12            left = dfs(node.left)
13            right = dfs(node.right)
14            rob_current = node.val + left[1] + right[1]
15            skip_current = max(left) + max(right)
16            return (rob_current, skip_current)
17        return max(dfs(root))

Complexity note: The time complexity is linear because we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.

  • 1Dynamic programming helps avoid redundant calculations.
  • 2Using recursion with memoization can optimize tree traversal.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.