Binary Trees Depth first: return a value up
366. House Robber III
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
Input: root = [5, 2, 9, 8, 1, 3, 0]
18Explanation: 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
Input: root = [6, null, 1, null, 2, null, 7]
13Explanation: Rob 6 and 7. The two houses between them are both skipped, which is allowed.
Example 3
Input: root = [1000000000, 0, 0, 1000000000, 1000000000]
3000000000Explanation: 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.
Constraints
1 ≤ number of nodes ≤ 1050 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
Clarifying questions
What you would ask an interviewer before writing any code.