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.
Without heavy light decomposition, I have been able to pass the three cases:
The part of the code that sets up the tree:
structnode{intparent=-1;intltree=-1;intrtree=-1;intdata;intmax;queue<int>neighbours;};intbuild(vector<node>&tree,vector<vector<int>>&edges){inttemp;// for swapping if need be// O(n) - setting up undirected acyclic graphfor(inti=0;i<edges.size();i++){tree[edges[i][0]].neighbours.push(edges[i][1]);tree[edges[i][1]].neighbours.push(edges[i][0]);}// O(n) - finding rootintroot=-1;for(inti=0;i<tree.size();i++){if(tree[i].neighbours.size()==2){root=i;break;}}// setting up the treequeue<int>rem_nodes;rem_nodes.push(root);while(!rem_nodes.empty()){node&curr_node=tree[rem_nodes.front()];while(!curr_node.neighbours.empty()){if(curr_node.parent!=curr_node.neighbours.front()){if(curr_node.ltree=-1){curr_node.ltree=curr_node.neighbours.front();rem_nodes.push(curr_node.ltree);tree[curr_node.ltree].parent=rem_nodes.front();}else{curr_node.rtree=curr_node.neighbours.front();rem_nodes.push(curr_node.rtree);tree[curr_node.rtree].parent=rem_nodes.front();}}curr_node.neighbours.pop();}rem_nodes.pop();}returnroot;}
It took a while to figure out that the parent may not have a smaller node-number than the child. For example:
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Heavy Light White Falcon
You are viewing a single comment's thread. Return to all comments →
Without heavy light decomposition, I have been able to pass the three cases:
The part of the code that sets up the tree:
It took a while to figure out that the parent may not have a smaller node-number than the child. For example: