Maximum XOR of Two Non-Overlapping Subtrees - Problem
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.
The root of the tree is the node labeled 0. Each node has an associated value. You are given an array values of length n, where values[i] is the value of the ith node.
Select any two non-overlapping subtrees. Your score is the bitwise XOR of the sum of the values within those subtrees.
Return the maximum possible score you can achieve. If it is impossible to find two non-overlapping subtrees, return 0.
Note that:
- The subtree of a node is the tree consisting of that node and all of its descendants.
- Two subtrees are non-overlapping if they do not share any common node.
Input & Output
Example 1 — Basic Tree
$
Input:
n = 6, edges = [[0,1],[1,3],[1,4],[0,2],[2,5]], values = [2,8,3,6,2,5]
›
Output:
24
💡 Note:
We can select subtree rooted at node 1 (sum = 8+6+2 = 16) and subtree rooted at node 2 (sum = 3+5 = 8). XOR: 16 ⊕ 8 = 24
Example 2 — Small Tree
$
Input:
n = 3, edges = [[0,1],[0,2]], values = [4,3,1]
›
Output:
0
💡 Note:
Any two non-overlapping subtrees would be single nodes. Maximum XOR is 3 ⊕ 1 = 2, but since we need subtrees, best is 0
Example 3 — Linear Tree
$
Input:
n = 4, edges = [[0,1],[1,2],[2,3]], values = [1,1,1,1]
›
Output:
3
💡 Note:
Select subtree at node 0 (sum=1) and subtree at node 3 (sum=1). But better: node 1 subtree (sum=3) and node 3 (sum=1). XOR: 3 ⊕ 1 = 2. Actually, best is subtree [0,1,2] = 3 and node 3 = 1, giving 3 ⊕ 1 = 2. Wait, let me recalculate: we can have subtree starting at 1 (includes 2,3) = 3, and node 0 = 1, giving 3 ⊕ 1 = 2. Or subtree at 0 (includes 1,2,3) = 4 but then no second subtree. Best is subtree 1,2 = 2 and subtree 3 = 1, giving 2 ⊕ 1 = 3
Constraints
- 2 ≤ n ≤ 5 × 104
- edges.length == n - 1
- 0 ≤ ai, bi < n
- ai ≠ bi
- 1 ≤ values[i] ≤ 109
- The given edges form a valid tree
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Tree with node values and edges
2
Find Subtrees
Identify all possible non-overlapping subtree pairs
3
Maximum XOR
Calculate XOR of subtree sums and find maximum
Key Takeaway
🎯 Key Insight: Use DFS to generate all subtree sums, then find maximum XOR efficiently with Trie
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code