AlgoFrames

House robber III

Standard · Write code · about 18 min

The houses of a village form a binary tree. root is the first house, and every house holds some money.

The thief cannot rob two houses that are linked by an edge, a parent and one of its children, or the police are called. Return the most money that can be stolen.

Example 1

Input:

[[3,2,3,null,3,null,1]]

Output:

7

Rob the root 3, the right-most house 3 and the house 1: 3 + 3 + 1 = 7.

Example 2

Input:

[[3,4,5,1,3,null,1]]

Output:

9

Rob the houses 4 and 5, the root's children: 4 + 5 = 9.

Constraints

  • 0 ≤ number of houses ≤ 10,000
  • 0 ≤ money in a house ≤ 10,000

Learn the idea first: Tree DP, a visual lesson.

More Tree DP problems