Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. class Solution:
  2. """
  3. @param start: The start of the edges set
  4. @param end: The end of the edges set
  5. @return: Return the subtree count
  6. """
  7. def getSubtreeCount(self, start, end):
  8. # Write your code here
  9. children_dict = {}
  10. real_root = start[0]
  11. for node_index in range(len(start)):
  12. parent_node = start[node_index]
  13. child_node = end[node_index]
  14. if parent_node not in children_dict:
  15. children_dict[parent_node] = [child_node]
  16. else:
  17. children_dict[parent_node].append(child_node)
  18. def subtree_count(root_node, children_dict):
  19. if root_node not in children_dict:
  20. return [1, 0]
  21. else:
  22. non_root_tree_num = 0
  23. root_tree_num = 1
  24. for children_node in children_dict[root_node]:
  25. child_root_tree_num, child_non_root_tree_num = subtree_count(children_node, children_dict)
  26. non_root_tree_num += (child_non_root_tree_num + child_root_tree_num)
  27. root_tree_num *= (child_root_tree_num + 1)
  28. return root_tree_num, non_root_tree_num
  29. output = subtree_count(real_root, children_dict)
  30. return (output[0] + output[1]) % 10000007
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement