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,dequedefcutTheTree(data,edges):# Create an adjacency list to represent the treenode=defaultdict(set)fora,binedges:node[a].add(b)node[b].add(a)n=len(data)subtree_sums=[None]*(n+1)# Perform DFS to calculate subtree sumsvisited=[False]*(n+1)stack=deque([1])visited[1]=Truewhilestack:i=stack[-1]# Check if any child nodes are unprocessedifany(subtree_sums[j]isNoneforjinnode[i]):forjinsorted(node[i]):ifnotvisited[j]:stack.append(j)visited[j]=Trueelse:node[i].remove(j)#Avoidrevisitingparentnodecontinue# Calculate the subtree sum for node isubtree_sums[i]=sum(subtree_sums[j]forjinnode[i])+data[i-1]stack.pop()# Total sum of all nodes in the treetotal_sum=subtree_sums[1]# Find the minimum difference between two parts of the treeforiinrange(2,n+1):diff=abs(total_sum-2*subtree_sums[i])min_diff=min(min_diff,diff)returnmin_diff
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
Cut the Tree
You are viewing a single comment's thread. Return to all comments →
Refined Version without building Node class