We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
We can make a mapping of each node, to the sum of their tree. In this case, the root node has a sum equal to the entire tree, and each other node the respective cost of their subtree.
If we cut at an edge, we spawn two subtrees: one where we just cut (with a sum equal to the mapping of that node) and a 'bigger' tree, with sum equal to the entire tree (i.e., mapping[1]) - the tree we just removed. With this idea, we can map each node to the sum of its tree in O(V + E), and then cut every edge once, perfoming the check in O(1), giving a further O(V + E).
The total time complexity then becomes O(V + E), with O(V + E) space, too.
defcutTheTree(data,edges):# Write your code hereadj=collections.defaultdict(list)foru,vinedges:adj[u].append(v)adj[v].append(u)lookup={}deftreeSum(node,par):ifnodeisNone:return0ifnodeinlookup:returnlookup[node]ans=data[node-1]forchinadj[node]:ifch==par:continueans+=treeSum(ch,node)lookup[node]=ansreturnanstreeSum(1,1)minDiff=float("inf")defminPart(node,par):nonlocalminDiffifnodeisNone:returnforchinadj[node]:ifch==par:continue# cut at childtree1=lookup[ch]tree2=lookup[1]-tree1diff=abs(tree1-tree2)minDiff=min(minDiff,diff)minPart(ch,node)minPart(1,1)returnminDiff
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Cut the Tree
You are viewing a single comment's thread. Return to all comments →
We can make a mapping of each node, to the sum of their tree. In this case, the root node has a sum equal to the entire tree, and each other node the respective cost of their subtree.
If we cut at an edge, we spawn two subtrees: one where we just cut (with a sum equal to the mapping of that node) and a 'bigger' tree, with sum equal to the entire tree (i.e., mapping[1]) - the tree we just removed. With this idea, we can map each node to the sum of its tree in O(V + E), and then cut every edge once, perfoming the check in O(1), giving a further O(V + E).
The total time complexity then becomes O(V + E), with O(V + E) space, too.