Given a tree, and the weights of all the nodes, the task is to find the root of the sub-tree whose weighted sum XOR with given integer X is maximum.
X = 15
Weight of sub-tree for parent 1 = ((-1) + (5) + (-2) + (-1) + (3)) XOR 15 = 4 XOR 15 = 11
Weight of sub-tree for parent 2 = ((5) + (-1) + (3)) XOR 15 = 7 XOR 15 = 8
Weight of sub-tree for parent 3 = -1 XOR 15 = -16
Weight of sub-tree for parent 4 = 3 XOR 15 = 12
Weight of sub-tree for parent 5 = -2 XOR 15 = -15
Node 4 gives the maximum sub-tree weighted sum XOR X.
Approach: Perform dfs on the tree, and for every node calculate the sub-tree weighted sum rooted at the current node then find the maximum (sum XOR X) value for a node.
Below is the implementation of the above approach:
- Time Complexity : O(N).
In dfs, every node of the tree is processed once and hence the complexity due to the dfs is O(N) if there are total N nodes in the tree. Therefore, the time complexity is O(N).
- Auxiliary Space : O(n).
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the root of the sub-tree whose weighted sum is minimum
- Find the root of the sub-tree whose weighted sum XOR with X is minimum
- Check if two nodes are in same subtree of the root node
- Find maximum GCD value from root to leaf in a Binary tree
- Find the maximum sum leaf to root path in a Binary Tree
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
- Find largest subtree sum in a tree
- Find GCD of each subtree of a given node in an N-ary Tree for Q queries
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Find the largest BST subtree in a given Binary Tree | Set 1
- Find largest subtree having identical left and right subtrees
- Find the largest Complete Subtree in a given Binary Tree
- Find the largest Perfect Subtree in a given Binary Tree
- Queries to find the Minimum Weight from a Subtree of atmost D-distant Nodes from Node X
- Maximum XOR with given value in the path from root to given node in the tree
- Maximum value of Bitwise AND from root to leaf in a Binary tree
- Root to leaf path with maximum distinct nodes
- Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
- Find root of the tree where children id sum for every node is given
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.