Skip to content
Decoder

House Robber III

Medium

Problem

The houses in a neighbourhood are arranged as a binary tree: each node is a house and its value is the cash inside. A thief can pick any set of houses, but if they take from two houses that are directly connected (a parent and its child), the alarm goes off.

Given the root, return the maximum amount the thief can take without triggering the alarm.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

Input
[3, 2, 3, null, 3, null, 1]
Output
7
Why
3 + 3 + 1

Example 2

Input
[3, 4, 5, 1, 3, null, 1]
Output
9
Why
4 + 5

Example 3

Input
[5]
Output
5

Constraints

  • 1 <= number of nodes <= 10^4
  • 0 <= Node.val <= 10^4

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.