#244MediumDynamic Programming· Tree DP: Take or Skip
Max Non-Adjacent Tree Bonus
Input format
`root`: the management chart as a binary tree in level order, with `null` for missing children (an empty array is an empty company).
Output format
A single integer: the largest total value of a set of employees in which no two are directly linked.
Examples
Input: root = [3, 2, 3, null, 3, null, 1]
Output: 7
Choose the root (3) and the two bottom nodes (3 and 1): 3 + 3 + 1 = 7. Choosing the two middle employees gives only 5.
Input: root = [3, 4, 5, 1, 3, null, 1]
Output: 9
Choosing the root and its grandchildren gives 3 + 1 + 3 + 1 = 8. Choosing the two children of the root, 4 and 5, gives 9, which is better.
Input: root = []
Output: 0
Nobody works there, so the total is 0.
Constraints
- 0 <= number of nodes <= 3000
- 0 <= value <= 10^4
- #tree
- #dynamic-programming
- #dfs
- #independent-set