Python 3.11+
Python recursion depth can fail on a long chain; iterative postorder is the boundary alternative, without changing the state meaning.
Verify in Python docs(opens in a new tab)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 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.
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.
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 traceImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 traceFor 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.
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))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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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))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. |
| 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.
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.
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 3.11+
Python recursion depth can fail on a long chain; iterative postorder is the boundary alternative, without changing the state meaning.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Compute an independent node-value sum on a rooted tree | O(n) | O(n) | n counts nodes reachable from the given root and h is that rooted tree's height. |
O(h) recursive stack, worst O(n); subtree_size_trace also returns O(n) output.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
A child's best state may select its root, violating the parent-child exclusion.
Prevent it: Use child_skip whenever the parent is taken.
take+=max(child_take,child_skip)take+=child_skipWhere you will hit this: Choose Non-Adjacent Tree Values(opens in a new tab)
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.
skip+=child_takeskip+=max(child_take,child_skip)Where you will hit this: Choose Non-Adjacent Tree Values(opens in a new tab)
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.
answer=takeanswer=max(take,skip)Where you will hit this: Maximum Contiguous Subarray Sum(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27
leetcode · checked 2026-07-12