Approach
Depth-first search
For Minimum Increments to Equalize Leaf Paths, 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
- 77 lines of Python from the credited upstream file minimum-increments-to-equalize-leaf-paths.py.
- The implementation visibly relies on sequence storage.
- 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 45class Solution(object):6 def minIncrease(self, n, edges, cost):7 """8 :type n: int9 :type edges: List[List[int]]10 :type cost: List[int]11 :rtype: int12 """13 def iter_dfs():14 result = n-115 mx = [0]*len(adj)16 stk = [(1, (0, -1))]17 while stk:18 step, (u, p) = stk.pop()19 if step == 1:20 stk.append((2, (u, p)))21 for v in reversed(adj[u]):22 if v != p:23 stk.append((1, (v, u)))24 elif step == 2:25 cnt = 026 for v in adj[u]:27 if v == p or mx[v] < mx[u]:28 continue29 if mx[v] > mx[u]:30 mx[u] = mx[v]31 cnt = 032 cnt += 133 result -= cnt34 mx[u] += cost[u]35 return result36 37 adj = [[] for _ in xrange(n)]38 for u, v in edges:39 adj[u].append(v)40 adj[v].append(u)41 return iter_dfs()42 43 44454647class Solution2(object):48 def minIncrease(self, n, edges, cost):49 """50 :type n: int51 :type edges: List[List[int]]52 :type cost: List[int]53 :rtype: int54 """55 def dfs(u, p):56 mx = cnt = 057 for v in adj[u]:58 if v == p:59 continue60 c = dfs(v, u)61 if c < mx:62 continue63 if c > mx:64 mx = c65 cnt = 066 cnt += 167 result[0] -= cnt68 return mx+cost[u]69 70 adj = [[] for _ in xrange(n)]71 for u, v in edges:72 adj[u].append(v)73 adj[v].append(u)74 result = [n-1]75 dfs(0, -1)76 return result[0]77