House Robber III
Explore how to apply backtracking techniques to solve the House Robber III challenge, where you maximize theft from houses arranged as a binary tree while avoiding connected targets. This lesson helps you develop a strategy to evaluate each node and determine the highest amount of money that can be robbed without triggering alerts.
We'll cover the following...
Statement
A thief has discovered a new neighborhood to target, where the houses can be represented as nodes in a binary tree. The money in the house is the data of the respective node. The thief can enter the neighborhood from a house represented as root of the binary tree. Each house has only one parent house. The thief knows that if he robs two houses that are directly connected, the police will be notified. The thief wants to know the maximum amount of money he can steal from the houses without getting caught by the police. The thief needs your help determining the maximum amount of money he can rob without alerting the police.
Constraints:
- The number of nodes in the tree is in the range .
-
node.data
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
House Robber III
What is the maximum amount we can rob from the following array?
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in main.js in the following coding playground.
// Definition of a binary tree node// class TreeNode {// constructor(data) {// this.data = data;// this.left = null;// this.right = null;// }// }import {TreeNode} from './ds_v1/BinaryTree.js';function rob(root) {// Replace this placeholder return statement with your codereturn -1;}export {rob}