Given a tree, and the weights of all the nodes, the task is to find the root of the sub-tree whose weighted sum is minimum.
Weight of sub-tree for parent 1 = ((-1) + (5) + (-2) + (-1) + (3)) = 4
Weight of sub-tree for parent 2 = ((5) + (-1) + (3)) = 7
Weight of sub-tree for parent 3 = -1
Weight of sub-tree for parent 4 = 3
Weight of sub-tree for parent 5 = -2
Node 5 gives the minimum sub-tree weighted sum.
Approach: Perform dfs on the tree, and for every node calculate the sub-tree weighted sum rooted at the current node then find the minimum sum 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 XOR with X is minimum
- Find the root of the sub-tree whose weighted sum XOR with X is maximum
- Check if two nodes are in same subtree of the root node
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Count the nodes of the given tree whose weighted string is a palindrome
- Count the nodes of the tree whose weighted string contains a vowel
- Count the nodes of a tree whose weighted string does not contain any duplicate characters
- Count the nodes of a tree whose weighted string is an anagram of the given string
- Count of leaf nodes of the tree whose weighted string is a palindrome
- Minimum difference between any two weighted nodes in Sum Tree of the given Tree
- Queries to find the Minimum Weight from a Subtree of atmost D-distant Nodes from Node X
- Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
- Find largest subtree sum in a tree
- Minimum cost to connect weighted nodes represented as array
- Minimum distance to visit all the nodes of an undirected weighted tree
- Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph
- Find Nth positive number whose digital root is X
- Minimum number of Nodes to be removed such that no subtree has more than K nodes
- Subtree with given sum in a Binary Tree
- Delete Edge to minimize subtree sum difference
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.