Maximum Distinct Path Sum in a Binary Tree Problem
Description
LeetCode Problem 3879.
You are given the root of a binary tree, where each node contains an integer value.
A valid path in the tree is a sequence of connected nodes such that:
- The path can start and end at any node in the tree.
- The path does not need to pass through the root.
- All node values along the path are distinct.
Return an integer denoting the maximum possible sum of node values among all valid paths.
Example 1:

Input: root = [2,2,1]
Output: 3
Explanation:
- The path 2 → 2 is invalid because the value 2 is not distinct.
- The maximum-sum valid path is 2 → 1, with a sum = 2 + 1 = 3.
Example 2:

Input: root = [1,-2,5,null,null,3,5]
Output: 9
Explanation:
- The path 3 → 5 → 5 is invalid due to duplicate value 5.
- The maximum-sum valid path is 1 → 5 → 3, with a sum = 1 + 5 + 3 = 9.
Example 3:

Input: root = [4,6,6,null,null,null,9]
Output: 19
Explanation:
- The path 6 → 4 → 6 → 9 is invalid because the value 6 appears more than once.
- The maximum-sum valid path is 4 → 6 → 9, with a sum = 4 + 6 + 9 = 19.
Constraints:
- The number of nodes in the tree is in the range
[1, 1000]. -1000 <= Node.val <= 1000
Solution
Approach: DFS + Hash Table
Treat the tree as an undirected graph. A hash table g maps each node to its neighbours: parent, left child and right child.
Every path has two ends, so it is enough to try every node as the start and extend the path in one direction. From a start node, a second DFS keeps a set vis of the values on the current path. If a node's value is already in vis (or the node is missing), that branch contributes 0. Otherwise add its value to vis, take the best result among its neighbours, then remove the value again and return the node's value plus that best result. Because values on the path are distinct, the DFS never walks back to a node it came from.
The answer is the largest result over all start nodes.
Complexity: time O(n^2), space O(n), where n is the number of nodes.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxSum(self, root: Optional[TreeNode]) -> int:
def dfs(node, p):
if node is None:
return
g[node] = [p, node.left, node.right]
dfs(node.left, node)
dfs(node.right, node)
def dfs2(node):
if node is None or node.val in vis:
return 0
vis.add(node.val)
res = node.val
best = 0
for nxt in g.get(node, []):
best = max(best, dfs2(nxt))
vis.remove(node.val)
res += best
return res
g = {}
dfs(root, None)
vis = set()
ans = -10**9
for node in g:
ans = max(ans, dfs2(node))
vis.clear()
return ans