binary-trees.py 1008 B

1234567891011121314151617181920212223242526272829303132
  1. def make_tree(item, depth):
  2. if not depth: return item, None, None
  3. item2 = item + item
  4. depth -= 1
  5. return item, make_tree(item2 - 1, depth), make_tree(item2, depth)
  6. def check_tree(node):
  7. item, left, right = node
  8. if not left: return item
  9. return item + check_tree(left) - check_tree(right)
  10. def main():
  11. min_depth = 4
  12. max_depth = max(min_depth + 2, 16)
  13. stretch_depth = max_depth + 1
  14. print "stretch tree of depth %d\t check:" % stretch_depth, check_tree(make_tree(0, stretch_depth))
  15. long_lived_tree = make_tree(0, max_depth)
  16. iterations = 2**max_depth
  17. for depth in range(min_depth, stretch_depth, 2):
  18. check = 0
  19. for i in range(1, iterations + 1):
  20. check += check_tree(make_tree(i, depth)) + check_tree(make_tree(-i, depth))
  21. print "%d\t trees of depth %d\t check:" % (iterations * 2, depth), check
  22. iterations /= 4
  23. print "long lived tree of depth %d\t check:" % max_depth, check_tree(long_lived_tree)
  24. main()