Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- This function finds out the answer to the question but only for the tree rooted at the given vertex.
- Basically, it finds the following 2 things
- 1. Number of nodes in the tree rooted at the given vertex (Number of nodes = Number of paths going down)
- 2. Sum of all paths starting from given vertex as root and going down.
- Complexity O(N)
- """
- def recurse(self, vertex):
- # Prevents the recursion from going into a cycle.
- self.visited[vertex] = 1
- # The two variables, n_paths and s_paths for this node i.e. vertex
- root_to_children_paths = 0
- sum_of_paths = 0
- # Iterate on all the children of this vertex and see which ones weren't visited before.
- for child in self.adj_list[vertex]:
- # If a child was not processed earlier, process it now.
- if child not in self.visited:
- # Mark the parent of this "child" as the "vertex".
- self.parent[child] = vertex
- # The result from recursing on the "child" node. We assume we would get the information we are looking for here.
- n_paths, s_paths = self.recurse(child)
- # Use the information from the recursive call to a subproblem, to solve the original problem
- # The number of paths would just increase by 1, (vertex --> child) is the extra path.
- root_to_children_paths += n_paths + 1
- # The explanation for this is there in the article.
- sum_of_paths += n_paths + s_paths + 1
- # Store the two variables we just calculated in external dictionaries. They would be used later on.
- self.distances_down[vertex] = sum_of_paths
- self.num_of_paths_down[vertex] = root_to_children_paths
- # Return the two variables, because recurse(vertex) could also have been a subproblem for yet another larger problem. :)
- return root_to_children_paths, sum_of_paths
Add Comment
Please, Sign In to add comment