Approach
Depth-first search
For Maximum XOR of Two Non-Overlapping Subtrees, 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
- 68 lines of Python from the credited upstream file 2479.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.
1class TrieNode:2 def __init__(self):3 self.children: list[TrieNode | None] = [None] * 24 5 6class BitTrie:7 def __init__(self, maxBit: int):8 self.maxBit = maxBit9 self.root = TrieNode()10 11 def insert(self, num: int) -> None:12 node = self.root13 for i in range(self.maxBit, -1, -1):14 bit = num >> i & 115 if not node.children[bit]:16 node.children[bit] = TrieNode()17 node = node.children[bit]18 19 def getMaxXor(self, num: int) -> int:20 maxXor = 021 node = self.root22 for i in range(self.maxBit, -1, -1):23 bit = num >> i & 124 toggleBit = bit ^ 125 if node.children[toggleBit]:26 maxXor = maxXor | 1 << i27 node = node.children[toggleBit]28 elif node.children[bit]:29 node = node.children[bit]30 else: 31 return 032 return maxXor33 34 35class Solution:36 def maxXor(self, n: int, edges: list[list[int]], values: list[int]) -> int:37 ans = 038 tree = [[] for _ in range(n)]39 treeSums = [0] * n40 41 for u, v in edges:42 tree[u].append(v)43 tree[v].append(u)44 45 46 def getTreeSum(u: int, prev: int) -> int:47 treeSum = values[u] + sum(getTreeSum(v, u) for v in tree[u] if v != prev)48 treeSums[u] = treeSum49 return treeSum50 51 def dfs(u: int, prev: int, bitTrie: BitTrie) -> None:52 nonlocal ans53 for v in tree[u]:54 if v == prev:55 continue56 57 ans = max(ans, bitTrie.getMaxXor(treeSums[v]))58 59 dfs(v, u, bitTrie)60 61 bitTrie.insert(treeSums[v])62 63 getTreeSum(0, -1)64 maxBit = int(math.log2(max(treeSums[1:])))65 66 dfs(0, -1, BitTrie(maxBit))67 return ans68