House Robber III
Problem Statement
A thief is robbing a row of houses that are arranged as a binary tree. The root is the entrance. Every other house has exactly one parent house.
Each house holds some money. The thief cannot rob two houses that are directly linked, meaning a house and one of its children. Two siblings, or a grandparent and a grandchild, are not directly linked, so both can be robbed.
Return the most money the thief can take in one night.
The root of a binary tree. It has between 1 and 10^4 nodes. Each node's value is the money in that house.
The largest total the thief can rob without taking two directly linked houses.
Rob the root (3), the 3 under the left child (3), and the 1 under the right child. That is 3 + 3 + 1 = 7. None of these three houses is a parent of another one.
Rob the two children of the root: 4 and 5. They are siblings, so they are not directly linked. Total 4 + 5 = 9.
- β’ The number of nodes is in the range [1, 10^4].
- β’ 0 β€ Node.val β€ 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
rob(node) = max(value + grandchildren, children), with no memory
Save each node's answer in an unordered_map, so each node is solved once
One post-order pass: each house returns best-if-robbed and best-if-skipped, no map
For one house, there are two choices. Rob it: take its value and add the best from its grandchildren, because the children are off-limits. Skip it: add the best from its two children, which are free. Return the larger of the two. The same subtrees are solved again and again.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.