oneby7

Binary Trees Depth first: return a value up

366. House Robber III

Medium

The houses in a neighbourhood are linked like a binary tree. Each node is a house, and its value is the amount of money inside. You are given root, the root node of the tree. A robber wants to take as much money as possible in one night.

A house shares an alarm with its parent and with its children. If two houses joined by a link are both robbed, the alarm goes off. So the robber never robs a node together with its parent or its children. Any other choice of houses is allowed, including robbing none.

Return the most money the robber can take.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

8215390

Input: root = [5, 2, 9, 8, 1, 3, 0]

Output: 18

Explanation: Rob 8 and 1 below the left child, and the right child 9: 8 + 1 + 9 = 18. Robbing every other level gives at most 5 + 8 + 1 + 3 + 0 = 17.

Example 2

6127

Input: root = [6, null, 1, null, 2, null, 7]

Output: 13

Explanation: Rob 6 and 7. The two houses between them are both skipped, which is allowed.

Example 3

10⁹010⁹10⁹0

Input: root = [1000000000, 0, 0, 1000000000, 1000000000]

Output: 3000000000

Explanation: Rob the root and the two houses on the bottom level. Both houses with no money are skipped.

Check your understanding

Work out the answer for this input before you write any code.

root = [2, 7, 3, null, 4, 6]

Constraints

  • 1 ≤ number of nodes ≤ 105
  • 0 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.