Approach
Depth-first search
For Delete Tree Nodes, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 46 lines of Python from the credited upstream file delete-tree-nodes.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import collections5 6 7class Solution(object):8 def deleteTreeNodes(self, nodes, parent, value):9 """10 :type nodes: int11 :type parent: List[int]12 :type value: List[int]13 :rtype: int14 """15 def dfs(value, children, x):16 total, count = value[x], 117 for y in children[x]:18 t, c = dfs(value, children, y)19 total += t20 count += c if t else 021 return total, count if total else 022 23 children = collections.defaultdict(list)24 for i, p in enumerate(parent):25 if i:26 children[p].append(i)27 return dfs(value, children, 0)[1]28 29 303132class Solution2(object):33 def deleteTreeNodes(self, nodes, parent, value):34 """35 :type nodes: int36 :type parent: List[int]37 :type value: List[int]38 :rtype: int39 """40 41 result = [1]*nodes42 for i in reversed(xrange(1, nodes)):43 value[parent[i]] += value[i]44 result[parent[i]] += result[i] if value[i] else 045 return result[0]46