treeTools.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """Generic tools for working with trees."""
  2. from math import ceil, log
  3. def build_n_ary_tree(leaves, n):
  4. """Build N-ary tree from sequence of leaf nodes.
  5. Return a list of lists where each non-leaf node is a list containing
  6. max n nodes.
  7. """
  8. if not leaves:
  9. return []
  10. assert n > 1
  11. depth = ceil(log(len(leaves), n))
  12. if depth <= 1:
  13. return list(leaves)
  14. # Fully populate complete subtrees of root until we have enough leaves left
  15. root = []
  16. unassigned = None
  17. full_step = n ** (depth - 1)
  18. for i in range(0, len(leaves), full_step):
  19. subtree = leaves[i : i + full_step]
  20. if len(subtree) < full_step:
  21. unassigned = subtree
  22. break
  23. while len(subtree) > n:
  24. subtree = [subtree[k : k + n] for k in range(0, len(subtree), n)]
  25. root.append(subtree)
  26. if unassigned:
  27. # Recurse to fill the last subtree, which is the only partially populated one
  28. subtree = build_n_ary_tree(unassigned, n)
  29. if len(subtree) <= n - len(root):
  30. # replace last subtree with its children if they can still fit
  31. root.extend(subtree)
  32. else:
  33. root.append(subtree)
  34. assert len(root) <= n
  35. return root