337. House Robber III
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the maximum amount of money a thief can rob from a set of houses arranged in a binary tree. The constraint is that if a house is robbed, its direct parent and direct children cannot be robbed. This structure and constraint strongly suggest a dynamic programming approach on the tree.
Solution
House Robber III in Python
# 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
from typing import Optional, Tuple
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
# The main function calls the helper and returns the max of the two possibilities for the root.
return max(self._rob_sub(root))
def _rob_sub(self, node: Optional[TreeNode]) -> Tuple[int, int]:
"""
Helper function to return a tuple of two values for a subtree.
Returns: (max_money_if_node_is_not_robbed, max_money_if_node_is_robbed)
"""
if not node:
return (0, 0)
# Recursively call for left and right children
left_res = self._rob_sub(node.left)
right_res = self._rob_sub(node.right)
# Option 1: Rob the current node.
# If we rob the current node, we cannot rob its children.
# So, we take the sum of values from not robbing the children.
rob_this_node = node.val + left_res[0] + right_res[0]
# Option 2: Do not rob the current node.
# If we don't rob the current node, we can take the maximum possible from its children.
# This means for each child, we can either rob it or not, so we take the max of the two options.
not_rob_this_node = max(left_res) + max(right_res)
return (not_rob_this_node, rob_this_node)
House Robber III in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int rob(TreeNode root) {
int[] result = robSub(root);
return Math.max(result[0], result[1]);
}
// Helper function to return an array of two values for a subtree.
// result[0]: max money if the root of this subtree is NOT robbed.
// result[1]: max money if the root of this subtree IS robbed.
private int[] robSub(TreeNode root) {
if (root == null) {
return new int[2]; // {0, 0}
}
// Recursively call for left and right children
int[] left = robSub(root.left);
int[] right = robSub(root.right);
// Option 1: Rob the current node.
// If we rob the current node, we cannot rob its children.
// So, we take the sum of values from not robbing the children.
int robThisNode = root.val + left[0] + right[0];
// Option 2: Do not rob the current node.
// If we don't rob the current node, we can take the maximum possible from its children.
// This means for each child, we can either rob it or not, so we take the max of the two options.
int notRobThisNode = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
return new int[]{notRobThisNode, robThisNode};
}
}
House Robber III in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int rob(TreeNode* root) {
std::vector<int> result = robSub(root);
return std::max(result[0], result[1]);
}
private:
// Helper function to return a pair of values for a subtree.
// result[0]: max money if the root of this subtree is NOT robbed.
// result[1]: max money if the root of this subtree IS robbed.
std::vector<int> robSub(TreeNode* root) {
if (!root) {
return {0, 0};
}
// Recursively call for left and right children
std::vector<int> left = robSub(root->left);
std::vector<int> right = robSub(root->right);
// Option 1: Rob the current node.
// If we rob the current node, we cannot rob its children.
// So, we take the sum of values from not robbing the children.
int rob_this_node = root->val + left[0] + right[0];
// Option 2: Do not rob the current node.
// If we don't rob the current node, we can take the maximum possible from its children.
// This means for each child, we can either rob it or not, so we take the max of the two options.
int not_rob_this_node = std::max(left[0], left[1]) + std::max(right[0], right[1]);
return {not_rob_this_node, rob_this_node};
}
};
House Robber III in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function rob(root: TreeNode | null): number {
// Helper function to return a tuple of two values for a subtree.
// Returns [max_money_if_not_robbed, max_money_if_robbed]
const dfs = (node: TreeNode | null): [number, number] => {
if (!node) {
return [0, 0];
}
// Recursively call for left and right children
const leftRes = dfs(node.left);
const rightRes = dfs(node.right);
// Option 1: Rob the current node.
// If we rob the current node, we cannot rob its children.
// So, we take the sum of values from not robbing the children.
const robThisNode = node.val + leftRes[0] + rightRes[0];
// Option 2: Do not rob the current node.
// If we don't rob the current node, we can take the maximum possible from its children.
// This means for each child, we can either rob it or not, so we take the max of the two options.
const notRobThisNode = Math.max(leftRes[0], leftRes[1]) + Math.max(rightRes[0], rightRes[1]);
return [notRobThisNode, robThisNode];
};
const result = dfs(root);
return Math.max(result[0], result[1]);
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.