Approach
Breadth-first search
For Maximum Distinct Path Sum in a Binary Tree, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 95 lines of Python from the credited upstream file maximum-distinct-path-sum-in-a-binary-tree.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
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 maxSum(self, root):7 """8 :type root: Optional[TreeNode]9 :rtype: int10 """11 def bfs():12 adj = [[]]13 vals = [root.val]14 q = [(root, -1)]15 while q:16 new_q = []17 for u, p in q:18 vals.append(u.val)19 adj.append([])20 i = len(adj)-121 if p != -1:22 adj[i].append(p)23 adj[p].append(i)24 for node in (u.left, u.right):25 if not node:26 continue27 new_q.append((node, i))28 q = new_q29 return adj, vals30 31 def iter_dfs(u):32 result = float("-inf")33 total = 034 lookup = set()35 stk = [(1, u, -1)]36 while stk:37 step, u, p = stk.pop()38 if step == 1:39 if vals[u] in lookup:40 continue41 stk.append((2, u, p))42 lookup.add(vals[u])43 total += vals[u]44 result = max(result, total)45 for v in adj[u]:46 if v == p:47 continue48 stk.append((1, v, u))49 elif step == 2:50 total -= vals[u]51 lookup.remove(vals[u])52 return result 53 54 adj, vals = bfs()55 return max(iter_dfs(u) for u in xrange(len(adj)))56 57 58596061class Solution2(object):62 def maxSum(self, root):63 """64 :type root: Optional[TreeNode]65 :rtype: int66 """67 def dfs1(u, p):68 vals.append(u.val)69 adj.append([])70 i = len(adj)-171 if p != -1:72 adj[i].append(p)73 adj[p].append(i)74 for node in (u.left, u.right):75 if not node:76 continue77 dfs1(node, i)78 79 def dfs2(u, p):80 if vals[u] in lookup:81 return float("-inf")82 lookup.add(vals[u])83 mx = 084 for v in adj[u]:85 if v == p:86 continue87 mx = max(mx, dfs2(v, u))88 lookup.remove(vals[u])89 return vals[u]+mx90 91 adj, vals = [], []92 dfs1(root, -1)93 lookup = set()94 return max(dfs2(u, -1) for u in xrange(len(adj)))95