/337. House Robber III

337. House Robber III

Medium
Dynamic Programming55.7% acceptance

Given a binary tree where each node contains a non-negative integer value, compute the maximum sum of node values such that no two directly connected nodes are both included in the sum. Return this maximum sum.

Example 1

Input: TreeNode(5, TreeNode(1), TreeNode(7))

Output: 12

Explanation: Rob nodes with values 5 and 7.

Example 2

Input: TreeNode(2, TreeNode(3, TreeNode(1)), TreeNode(4))

Output: 7

Explanation: Rob nodes with values 3 and 4.

Constraints

  • 1 <= number of nodes <= 10_000
  • 0 <= node value <= 10_000
Python (current runtime)

Case 1

Input: TreeNode(6, TreeNode(2, TreeNode(1)), TreeNode(3))

Expected: 9

Case 2

Input: TreeNode(8, TreeNode(4, None, TreeNode(2)), TreeNode(5))

Expected: 11

Case 3

Input: TreeNode(10, TreeNode(1, TreeNode(2)), TreeNode(3, None, TreeNode(4)))

Expected: 16