Leetcode #2479: Maximum XOR of Two Non-Overlapping Subtrees
In this guide, we solve Leetcode #2479 Maximum XOR of Two Non-Overlapping Subtrees in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
There is an undirected tree with n nodes labeled from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Tree, Depth-First Search, Graph, Trie
Intuition
The data forms a graph, so we should explore nodes and edges systematically.
A traversal ensures we visit each node once while maintaining the needed state.
Approach
Build an adjacency list and traverse with BFS or DFS.
Aggregate results as you visit nodes.
Steps:
- Build the graph.
- Traverse with BFS/DFS.
- Accumulate the required output.
Example
Input: n = 6, edges = [[0,1],[0,2],[1,3],[1,4],[2,5]], values = [2,8,3,6,2,5]
Output: 24
Explanation: Node 1's subtree has sum of values 16, while node 2's subtree has sum of values 8, so choosing these nodes will yield a score of 16 XOR 8 = 24. It can be proved that is the maximum possible score we can obtain.
Python Solution
class Trie:
def __init__(self):
self.children = [None] * 2
def insert(self, x):
node = self
for i in range(47, -1, -1):
v = (x >> i) & 1
if node.children[v] is None:
node.children[v] = Trie()
node = node.children[v]
def search(self, x):
node = self
res = 0
for i in range(47, -1, -1):
v = (x >> i) & 1
if node is None:
return res
if node.children[v ^ 1]:
res = res << 1 | 1
node = node.children[v ^ 1]
else:
res <<= 1
node = node.children[v]
return res
class Solution:
def maxXor(self, n: int, edges: List[List[int]], values: List[int]) -> int:
def dfs1(i, fa):
t = values[i]
for j in g[i]:
if j != fa:
t += dfs1(j, i)
s[i] = t
return t
def dfs2(i, fa):
nonlocal ans
ans = max(ans, tree.search(s[i]))
for j in g[i]:
if j != fa:
dfs2(j, i)
tree.insert(s[i])
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
s = [0] * n
dfs1(0, -1)
ans = 0
tree = Trie()
dfs2(0, -1)
return ans
Complexity
The time complexity is O(V+E). The space complexity is O(V).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.