Problem solution · Python

Maximum Distinct Path Sum in a Binary Tree

Maximum Distinct Path Sum in a Binary Tree: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Breadth-first search
Source
Kamyu LeetCode Solutions
Length
95 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. 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.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeMaximum Distinct Path Sum in a Binary Tree · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n^2)# Space: O(n) # bfs, iterative dfsclass Solution(object):    def maxSum(self, root):        """        :type root: Optional[TreeNode]        :rtype: int        """        def bfs():            adj = [[]]            vals = [root.val]            q = [(root, -1)]            while q:                new_q = []                for u, p in q:                    vals.append(u.val)                    adj.append([])                    i = len(adj)-1                    if p != -1:                        adj[i].append(p)                        adj[p].append(i)                    for node in (u.left, u.right):                        if not node:                            continue                        new_q.append((node, i))                q = new_q            return adj, vals         def iter_dfs(u):            result = float("-inf")            total = 0            lookup = set()            stk = [(1, u, -1)]            while stk:                step, u, p = stk.pop()                if step == 1:                    if vals[u] in lookup:                        continue                    stk.append((2, u, p))                    lookup.add(vals[u])                    total += vals[u]                    result = max(result, total)                    for v in adj[u]:                        if v == p:                            continue                        stk.append((1, v, u))                elif step == 2:                    total -= vals[u]                    lookup.remove(vals[u])            return result             adj, vals = bfs()        return max(iter_dfs(u) for u in xrange(len(adj)))  # Time:  O(n^2)# Space: O(n)# dfsclass Solution2(object):    def maxSum(self, root):        """        :type root: Optional[TreeNode]        :rtype: int        """        def dfs1(u, p):            vals.append(u.val)            adj.append([])            i = len(adj)-1            if p != -1:                adj[i].append(p)                adj[p].append(i)            for node in (u.left, u.right):                if not node:                    continue                dfs1(node, i)                def dfs2(u, p):            if vals[u] in lookup:                return float("-inf")            lookup.add(vals[u])            mx = 0            for v in adj[u]:                if v == p:                    continue                mx = max(mx, dfs2(v, u))            lookup.remove(vals[u])            return vals[u]+mx                    adj, vals = [], []        dfs1(root, -1)        lookup = set()        return max(dfs2(u, -1) for u in xrange(len(adj))) 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗