437. Maximum XOR of Two Non Overlapping Subtrees

An undirected tree with n nodes labelled 0 through n-1 is present. Given the integer n and a 2D integer array of edges of length n - 1, you can see that there is an edge between nodes ai and bi in the tree by looking at edges[i] = [ai, bi]. The node with the number 0 is the tree's root.

Every node has a corresponding value. An array of length n is provided to you, with values[i] being the value of the ith node.

Choose any two subtrees that don't overlap. The bitwise XOR of the sum of the values in those subtrees is your score.

Give back the highest score you are capable of obtaining. Return 0 if two nonoverlapping subtrees cannot be found. 

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.

Example 1:

Input : n = 5, edges = [ [0, 1], [1, 2], [2, 3], [3, 4] ], values = [1, 2, 3, 4, 5]

Output : 0

Explanation :

The given tree is a skewed tree and thus we cannot obtain two non overlapping subtrees in it.

So we return 0.

Example 2:

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.

Now Your Turn!

Pick the correct output for the given input

Input : n = 6, edges = [ [0, 1], [0, 2], [2, 3], [0, 4], [2, 5] ] , values = [5, 1, 8, 2, 3, 7]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 2 <= n <= 5 * 104
  • edges.length == n - 1
  • 0 <= ai, bi < n
  • values.length == n
  • 1 <= values[i] <= 109
  • It is guaranteed that edges represents a valid tree.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution{
public:
long long maxXor(int n, vector<vector<int>> &edges, vector<int> &values){
//your code goes here
}
};
Test Case

Input:

Edges
N
Values