Skip to contentKEEP THE CRAFTTHE SANCTUARY

Tree DP

Solve children before their parent and return a complete subtree summary. For nonadjacent node selection, each subtree returns separate take-root and skip-root optima.

1 practice exercise1 interview problem

Recognize it when A rooted tree objective combines answers from child subtrees.

Checking your account…

Tree DP Code Labs

Return Information the Parent Can Legally Use

Tree DP is more than a traversal order: each completed subtree returns a summary sufficient for its parent. Counting subtree size needs one number. Maximizing values with no selected parent-child pair needs two numbers, because the parent must know whether the child’s root is selected. Returning only the child’s unrestricted maximum would lose that condition.

Observe Children Completing First

The size trace recursively sums completed child sizes, adds one for the current node, then records its event. A leaf returns size one. The given child lists must describe a rooted tree with valid indices, no cycles and no shared descendants. The sentinel root -1 denotes an empty tree.

Trace Tree DP Summaries

Reference
def subtree_size_trace(children,root):
    trace=[]
    def solve(node):
        size=1+sum(solve(child) for child in children[node]);trace.append([node,size]);return size
    if root!=-1:solve(root)
    return trace
Practice

Implement subtree_size_trace(children,root). children describes a rooted tree with valid node indices, no cycles and no shared descendants; root=-1 denotes an empty tree. Return [node,size] when each node completes in postorder.

Public tests

  • Combine completed child summaries

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Tree DP Summaries

def subtree_size_trace(children,root):
    trace=[]
    def solve(node):
        size=1+sum(solve(child) for child in children[node]);trace.append([node,size]);return size
    if root!=-1:solve(root)
    return trace

Condition the Optimum on the Root Choice

For a subtree, take starts with the current node’s value and can add only each child’s skip. skip starts at zero and can add the better of each child’s two states. Once the parent choice is fixed, child subtrees are independent, so compatible optima add. These two cases partition every legal selection.

Maximum Independent Tree Sum

Reference
def max_independent_sum(values,children,root):
    if root==-1:return 0
    def solve(node):
        take=values[node];skip=0
        for child in children[node]:
            child_take,child_skip=solve(child);take+=child_skip;skip+=max(child_take,child_skip)
        return take,skip
    return max(solve(root))
Practice

Implement max_independent_sum(values,children,root). values aligns with a rooted tree in children with valid node indices, no cycles and no shared descendants; root=-1 denotes an empty tree. Choose the maximum node-value sum with no parent-child pair both chosen; selecting no nodes is allowed.

Public tests

  • Return take and skip per subtree

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Maximum Independent Tree Sum

def max_independent_sum(values,children,root):
    if root==-1:return 0
    def solve(node):
        take=values[node];skip=0
        for child in children[node]:
            child_take,child_skip=solve(child);take+=child_skip;skip+=max(child_take,child_skip)
        return take,skip
    return max(solve(root))

Let a Skipped Parent Choose Each Child Independently

Predict max_independent_sum([4,6,5,3], [[1,2],[],[3],[]], 0). Node 2 has child 3, so its take and skip summaries differ.

Step Executed statement State Why
1 take=values[node]; skip=0; return take,skip leaf 1 returns (6,0) Taking a leaf earns its value; skipping it earns zero.
2 take+=child_skip; skip+=max(child_take,child_skip) root after child 1: take=4; skip=6 A selected root cannot also select node 1.
3 take=values[node]; skip=0; return take,skip leaf 3 returns (3,0) Its complete summary is ready before node 2 combines it.
4 take+=child_skip; skip+=max(child_take,child_skip) node 2: take=5+0=5; skip=0+3=3 Taking node 2 excludes child 3; skipping it may take that child.
5 take+=child_skip; skip+=max(child_take,child_skip) root after child 2: take=7; skip=11 The two child subtrees choose independently once the root condition is fixed.
6 return max(solve(root)) return=max(7,11)=11 Skipping the root gives the larger legal total.
Print Output
print(max_independent_sum([4,6,5,3],[[1,2],[],[3],[]],0)) 11

At the overall root, either condition is permitted, so return their maximum. Selecting no node is allowed: skip protects the result from being forced negative when values are negative. The function preserves values and child lists.

Keep the Tree Assumption Visible

A shared descendant in a DAG belongs to two child summaries and would be counted twice. A cycle would recurse indefinitely. Adding a cache does not repair the independent-subtree proof for either case. The tree contract, rather than memoization alone, makes one postorder pass sufficient.

Choose the Summary in an Interview

These Labs illustrate scalar and conditioned summaries, not a universal take/skip recurrence. Path objectives may need an extendable path plus a separate best-anywhere result. All-root answers may need rerooting with parent-side information. For the current fixed-size pair, every node and edge is processed once: O(n) time and O(h) call-stack space, worst O(n) on a chain. An iterative postorder avoids Python depth limits while preserving the same child-before-parent dependencies.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Compute an independent node-value sum on a rooted treeO(n)O(n)n counts nodes reachable from the given root and h is that rooted tree's height.

Space

O(h) recursive stack, worst O(n); subtree_size_trace also returns O(n) output.

Assumptions

  • Each tree edge contributes one constant-size child combination; no memo cache is needed because every child has one parent.
  • The input child lists are supplied by the caller, not allocated by these Labs.
  • Python recursion depth can fail on a long chain; iterative postorder is the boundary alternative, without changing the state meaning.

Invariants Worth Saying Aloud

  1. A child summary is complete before the parent uses it.
  2. take is the best subtree total conditioned on selecting that subtree's root.
  3. skip is the best subtree total conditioned on not selecting its root.
  4. Selecting a parent allows only each child's skip; skipping a parent allows each child's better state.

When To Use Or Avoid Tree DP

Use It When

  • The input is a rooted tree with independent child subtrees and valid child indices.
  • A bounded summary captures every condition needed at the parent-child boundary.

Choose Another Tool When

  • The input is a general graph with cycles or shared descendants; independent subtree addition can double count.
  • The answer is needed for every possible root; a second parent-side pass may require rerooting.
  • A parent needs more conditions than the proposed summary includes.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Adding an unrestricted child optimum to a taken parent

A child's best state may select its root, violating the parent-child exclusion.

Prevent it: Use child_skip whenever the parent is taken.

Avoid

take+=max(child_take,child_skip)

Use instead

take+=child_skip

Forcing children to be taken when the parent is skipped

A skipped parent permits either child condition; negative-valued children may be better skipped.

Prevent it: Add max(child_take,child_skip) independently for each child.

Avoid

skip+=child_take

Use instead

skip+=max(child_take,child_skip)

Forcing the overall root to be selected

The returned pair is conditioned, and the problem does not require the root condition take.

Prevent it: Choose the better legal root outcome after both summaries are complete.

Avoid

answer=take

Use instead

answer=max(take,skip)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.