Given an undirected tree whose each node is associated with a weight. We need to delete an edge in such a way that difference between sum of weight in one subtree to sum of weight in other subtree is minimized.
In above tree, We have 6 choices for edge deletion, edge 0-1, subtree sum difference = 21 - 2 = 19 edge 0-2, subtree sum difference = 14 - 9 = 5 edge 0-3, subtree sum difference = 15 - 8 = 7 edge 2-4, subtree sum difference = 20 - 3 = 17 edge 2-5, subtree sum difference = 18 - 5 = 13 edge 3-6, subtree sum difference = 21 - 2 = 19
We can solve this problem using DFS. One simple solution is to delete each edge one by one and check subtree sum difference. Finally choose the minimum of them. This approach takes quadratic amount of time. An efficient method can solve this problem in linear time by calculating the sum of both subtrees using total sum of the tree. We can get the sum of other tree by subtracting sum of one subtree from the total sum of tree, in this way subtree sum difference can be calculated at each node in O(1) time. First we calculate the weight of complete tree and then while doing the DFS at each node, we calculate its subtree sum, by using these two values we can calculate subtree sum difference.
In below code, another array subtree is used to store sum of subtree rooted at node i in subtree[i]. DFS is called with current node index and parent index each time to loop over children only at each node.
Please see below code for better understanding.
This article is contributed by Utkarsh Trivedi. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Edge Coloring of a Graph
- Even size subtree in n-ary tree
- Queries for DFS of a subtree in a tree
- Queries for M-th node in the DFS of subtree
- Subtree of all nodes in a tree using DFS
- Minimum edge reversals to make a root
- Program to Calculate the Edge Cover of a Graph
- Check if removing a given edge disconnects a graph
- Paths to travel each nodes using each edge (Seven Bridges of Königsberg)
- Maximum edge removal from tree to make even forest
- Maximize number of nodes which are not part of any edge in a Graph
- Remove all outgoing edges except edge with minimum weight
- Tree, Back, Edge and Cross Edges in DFS of Graph
- Shortest Path in a weighted Graph where weight of an edge is 1 or 2
- Find the Kth node in the DFS traversal of a given subtree in a Tree
Improved By : PranchalKatiyar