KatInterview

Maximum Non-Adjacent Node Value Sum in Binary Tree

Dynamic ProgrammingAuto-graded · 20 test cases
HardAuto-gradedDynamic Programmingtrees-graphsdynamic-programmingarrays

Last updated

Find the maximum total node sum from a binary tree represented as a level-order list such that no two selected nodes share a parent-child edge.

Given a binary tree serialized as a level-order list, calculate the maximum possible total value of a subset of tree nodes under the condition that no two selected nodes are directly connected by an edge (i.e., you cannot choose both a parent node and its immediate child).

The tree input is provided as a list a using standard level-order representation (where None denotes a missing node).

If choosing no nodes yields a higher total sum (or if the tree is empty), the result should be 0.

Constraints

  • 0 <= len(a) <= 10,000
  • Each non-null element in a is an integer in the range [-1,000, 1,000].
  • The list a represents a valid binary tree in level-order layout.

Examples

Example 1

Input: max_non_adjacent_sum([10, 5, 15, 1, 8, None, 7])

Output: 26

Example 2

Input: max_non_adjacent_sum([3, 4, 5, 1, 3, None, 1])

Output: 9

Hints

Hint 1

Consider computing two dynamic programming values for each subtree: the maximum sum when the subtree's root is included, and when it is excluded.

Hint 2

If a parent node is chosen, neither of its direct children may be chosen. If a parent node is excluded, its children can independently be either chosen or excluded.

Hint 3

Process nodes from the bottom up (e.g., using post-order traversal or by reversing a top-down search order) to ensure child results are ready before calculating their parent.