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.
classResult{staticList<List<Integer>>graph;staticList<Integer>data;staticintroot,res,total;publicstaticvoidcreate(List<List<Integer>>edges,intn){for(inti=0;i<=n;i++){graph.add(newArrayList<Integer>());// Change to LinkedList<Integer>()}for(List<Integer>e:edges){graph.get(e.get(0)).add(e.get(1));graph.get(e.get(1)).add(e.get(0));}}privatestaticintdfs(intr,boolean[]vis){vis[r]=true;if(graph.get(r).size()==0)return0;intsum=0;for(inti:graph.get(r)){if(!vis[i])sum+=dfs(i,vis);}sum+=data.get(r-1);res=Math.min(res,Math.abs(total-sum*2));returnsum;}publicstaticintcutTheTree(List<Integer>data,List<List<Integer>>edges){// Write your code hereints=0;graph=newArrayList<>();root=-1;res=Integer.MAX_VALUE;for(inti:data)s+=i;total=s;create(edges,data.size());Result.data=data;intv=dfs(1,newboolean[data.size()+2]);returnres;}}
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 →