Maximum Non-Adjacent Node Value Sum in Binary Tree
Dynamic ProgrammingAuto-graded · 20 test casesLast 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
ais an integer in the range[-1,000, 1,000]. - The list
arepresents 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is an instance of finding the Maximum Weight Independent Set on a tree, which can be solved efficiently using Tree Dynamic Programming.
For any node $u$ in the tree, we define two states for the subtree rooted at $u$:
take: The maximum sum obtainable from $u$'s subtree when node $u$ is selected.skip: The maximum sum obtainable from $u$'s subtree when node $u$ is skipped.
Recurrence Relations
- If node $u$ is selected (
take): Neither of its direct children can be selected. Therefore, for each child $c$, we must use itsskipvalue: $$\text{take}(u) = \text{val}(u) + \sum_{c \in \text{children}(u)} \text{skip}(c)$$ - If node $u$ is skipped (
skip): Its children are under no restriction regarding $u$. Each child $c$ can be independently included or excluded to maximize score: $$\text{skip}(u) = \sum_{c \in \text{children}(u)} \max(\text{take}(c), \text{skip}(c))$$
Implementation Details
- Tree Reconstruction: First, convert the level-order input array into an explicit graph or parent-child adjacency structure.
- Traversal Order: To evaluate children before their parents (bottom-up DP) without relying on deep recursion that could hit stack overflow limits on skewed trees, perform a top-down pre-order traversal stack to record node ordering, then process nodes in reverse order.
- State Computation: Iterate through the reversed order, computing
skipandtakefor each node based on its children's stored DP values. - Final Answer: Return $\max(\text{take}(\text{root}), \text{skip}(\text{root}))$. If the tree is empty or all paths yield negative sums, the maximum non-adjacent subset selection (which can be the empty set) defaults to
0.
Complexity
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the number of nodes in the binary tree. Rebuilding the tree structure and processing DP states both take linear time.
- Space Complexity: $\mathcal{O}(N)$ to store tree structures, node order, and DP state arrays.
Python Reference Solution
from collections import deque
from typing import List, Optional
def max_non_adjacent_sum(a: List[Optional[int]]) -> int:
if not a or a[0] is None:
return 0
# Build node structure: [val, left_idx, right_idx]
nodes = [[a[0], -1, -1]]
queue = deque([0])
pos = 1
while queue and pos < len(a):
parent = queue.popleft()
for side in (1, 2):
if pos >= len(a):
break
val = a[pos]
pos += 1
if val is not None:
child = len(nodes)
nodes.append([val, -1, -1])
nodes[parent][side] = child
queue.append(child)
# Topological order via DFS (pre-order stack) to reverse for post-order processing
order = []
stack = [0]
while stack:
node = stack.pop()
order.append(node)
left, right = nodes[node][1], nodes[node][2]
if left != -1:
stack.append(left)
if right != -1:
stack.append(right)
# Bottom-up DP: dp[i] = [best_when_skipped, best_when_taken]
dp = [[0, 0] for _ in nodes]
for node in reversed(order):
val, left, right = nodes[node]
left_skip, left_take = dp[left] if left != -1 else (0, 0)
right_skip, right_take = dp[right] if right != -1 else (0, 0)
dp[node][0] = max(left_skip, left_take) + max(right_skip, right_take)
dp[node][1] = val + left_skip + right_skip
return max(dp[0])