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.
fromcollectionsimportdefaultdict,dequeclassNode:def__init__(self,num,val):self.num=num#Nodenumberself.val=val#Nodevalueself.data=None#Cachedsubtreesumself.children=set()#Childrennodesdeftree_sum(self):"""Calculate subtree sum."""ifself.dataisNone:#Ifnotcalculatedyetifnotself.children:#Ifleafnodeself.data=self.valelse:self.data=sum(child.dataforchildinself.children)+self.valreturnself.datadefbuild_tree_and_calculate_sums(data,edges):"""Build tree and calculate subtree sums."""connections=defaultdict(set)#Nodeconnectionsfora,binedges:connections[a].add(b)connections[b].add(a)n=len(data)nodes={i:Node(i,data[i-1])foriinrange(1,n+1)}#DFStraversaltosetupnoderelationshipsandcalculatesubtreesumsvisited=[False]*(n+1)dq=deque([1])visited[1]=Truewhiledq:current_node=dq.pop()forjinconnections[current_node]:ifnotvisited[j]:visited[j]=Truenodes[current_node].children.add(nodes[j])dq.append(j)#Calculatesubtreesumsdq=deque([nodes[1]])whiledq:curr_node=dq[-1]ifcurr_node.dataisNone:ifall(child.dataisnotNoneforchildincurr_node.children):curr_node.tree_sum()dq.pop()else:dq.extend(childforchildincurr_node.children)returnnodesdefcutTheTree(data,edges):"""Calculate minimum difference between two subtrees' sums after a cut."""nodes=build_tree_and_calculate_sums(data,edges)# Calculate total sum of the tree rooted at the first nodetotal_sum=nodes[1].tree_sum()#Calculateminimumdifferencebetweensumsoftwosubtreesmin_diff=total_sumforiinrange(2,len(nodes)+1):min_diff=min(min_diff,abs(total_sum-2*nodes[i].tree_sum()))returnmin_diff
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 →