Guest User

Untitled

a guest
Jun 20th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. """
  2. This function finds out the answer to the question but only for the tree rooted at the given vertex.
  3. Basically, it finds the following 2 things
  4.  
  5. 1. Number of nodes in the tree rooted at the given vertex (Number of nodes = Number of paths going down)
  6. 2. Sum of all paths starting from given vertex as root and going down.
  7.  
  8. Complexity O(N)
  9. """
  10. def recurse(self, vertex):
  11. # Prevents the recursion from going into a cycle.
  12. self.visited[vertex] = 1
  13.  
  14. # The two variables, n_paths and s_paths for this node i.e. vertex
  15. root_to_children_paths = 0
  16. sum_of_paths = 0
  17.  
  18. # Iterate on all the children of this vertex and see which ones weren't visited before.
  19. for child in self.adj_list[vertex]:
  20. # If a child was not processed earlier, process it now.
  21. if child not in self.visited:
  22. # Mark the parent of this "child" as the "vertex".
  23. self.parent[child] = vertex
  24. # The result from recursing on the "child" node. We assume we would get the information we are looking for here.
  25. n_paths, s_paths = self.recurse(child)
  26.  
  27. # Use the information from the recursive call to a subproblem, to solve the original problem
  28. # The number of paths would just increase by 1, (vertex --> child) is the extra path.
  29. root_to_children_paths += n_paths + 1
  30.  
  31. # The explanation for this is there in the article.
  32. sum_of_paths += n_paths + s_paths + 1
  33.  
  34. # Store the two variables we just calculated in external dictionaries. They would be used later on.
  35. self.distances_down[vertex] = sum_of_paths
  36. self.num_of_paths_down[vertex] = root_to_children_paths
  37.  
  38. # Return the two variables, because recurse(vertex) could also have been a subproblem for yet another larger problem. :)
  39. return root_to_children_paths, sum_of_paths
Add Comment
Please, Sign In to add comment