DSA Factory
Free Mixed sets lessonsMixed sets · Stage 2 · Set 3 · Step 1

Robbing the tree

Choose the nodes of a tree with the largest total value so that no two chosen nodes are parent and child, by returning two numbers from each subtree. About 20 minutes.

Two answers per node

You may pick nodes, but never a parent together with one of its children. For each node, you need two answers about its subtree: the best total if this node is picked, and the best total if it is not.

The two answers differ in what they allow the children to do, so a single number is not enough information for the parent.

Take: best total with this node picked.
Skip: best total with this node not picked.
In code
take = house + skip_a + skip_b
skip = max(a, b)
Best haul from the tree 3, 9, 8, 1, none, none, 2.
19382
leaves
1: (1, 0) 2: (2, 0)

The leaves 1 and 2: take is their value, skip is 0.

Move 1 of 3

Combine the children

If you take the node, both children must be skipped, so add the node's value to the children's skip answers.

If you skip the node, each child is free: use the better of its take and skip answers, and add the two. An empty subtree has take and skip both zero. The answer for the whole tree is the better of the root's two numbers.

Take a node: children must be skipped.
Skip a node: children choose freely.
In code
best = max(take, skip)
Quick check

A node is taken. What happens to its children?

  1. AThey must be skipped, so only their skip answers are used
  2. BThey choose freely
  3. CThey must be taken too
Show the answer

They must be skipped, so only their skip answers are used. A parent and its child may not both be picked.

Your problem

House robber on a tree

Thieves find a neighbourhood whose houses form a binary tree, the root being the entrance. Each house holds an amount of money. If two directly linked houses (a parent and its child) are both robbed, the alarm sounds. Given the root, return the largest total that can be robbed without setting off the alarm.

Example
root = [3, 2, 3, null, 3, null, 1] → 7

0 ≤ number of nodes ≤ 10,000 · 0 ≤ node.val ≤ 10,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve