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.
Use a Depth First Search (DFS) to calculate the size of each subtree.
Count the number of subtrees with even numbers of nodes.
The number of edges to remove is the number of even subtrees minus 1 (since we don't count the root's subtree).
Solution
Here is the PHP code:
<?phpfunctionevenForest($t_nodes,$t_edges,$t_from,$t_to){$graph=[];// Initialize graphfor($i=1;$i<=$t_nodes;$i++){$graph[$i]=[];}// Build adjacency listfor($i=0;$i<count($t_from);$i++){$graph[$t_from[$i]][]=$t_to[$i];$graph[$t_to[$i]][]=$t_from[$i];}// Array to store the size of each subtree$subtreeSize=array_fill(1,$t_nodes,0);functiondfs($node,$parent,&$graph,&$subtreeSize){$subtreeSize[$node]=1;// Include the node itselfforeach($graph[$node]as$neighbor){if($neighbor!=$parent){$subtreeSize[$node]+=dfs($neighbor,$node,$graph,$subtreeSize);}}return$subtreeSize[$node];}// Start DFS from node 1 (arbitrary choice for the root)dfs(1,-1,$graph,$subtreeSize);$removableEdges=0;// Count removable edgesfor($i=2;$i<=$t_nodes;$i++){if($subtreeSize[$i]%2==0){$removableEdges++;}}return$removableEdges;}// Example usage:$t_nodes=10;$t_edges=9;$t_from=[2,3,4,5,6,7,8,9,10];$t_to=[1,1,2,2,3,3,4,4,5];echoevenForest($t_nodes,$t_edges,$t_from,$t_to);// Output should be 2?>
Explanation:
Graph Construction: We use an adjacency list to represent the graph.
DFS Traversal: We traverse the graph using DFS, calculating the size of each subtree.
Subtree Size Calculation: The size of each subtree is stored in the $subtreeSize array.
Count Removable Edges: We iterate through each node (except the root) and count subtrees of even size.
This solution assumes that the tree is given in a 1-based index as in the example. If your tree nodes are 0-based, you should adjust the code accordingly.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Even Tree
You are viewing a single comment's thread. Return to all comments →
Approach
Solution
Here is the PHP code:
Explanation:
$subtreeSize
array.This solution assumes that the tree is given in a 1-based index as in the example. If your tree nodes are 0-based, you should adjust the code accordingly.