binarytrees.scm 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. (define-constant min-depth :: int 4)
  2. (define-class TreeNode ()
  3. (left :: TreeNode)
  4. (right :: TreeNode)
  5. (item :: int)
  6. ((item-check) :: int
  7. (if (eq? left #!null)
  8. item
  9. (+ item (- (left:item-check) (right:item-check))))))
  10. (define (bottom-up-tree (item :: int) (depth :: int)) :: TreeNode
  11. (if (= depth 0)
  12. (TreeNode item: item)
  13. (let ((item2 :: int (* 2 item))
  14. (depth-1 :: int (- depth 1)))
  15. (TreeNode left: (bottom-up-tree (- item2 1) depth-1)
  16. right: (bottom-up-tree item2 depth-1)
  17. item: item))))
  18. (define (test (n :: int))
  19. (define max-depth :: int (if (> (+ min-depth 2) n) (+ min-depth 2) n))
  20. (define stretch-depth (+ max-depth 1))
  21. (format #t "stretch tree of depth ~d~c check: ~d~%" stretch-depth #\tab
  22. ((bottom-up-tree 0 stretch-depth):item-check))
  23. (define long-lived-tree (bottom-up-tree 0 max-depth))
  24. (do ((d :: int min-depth (+ d 2)))
  25. ((> d max-depth) #!void)
  26. (let ((iterations :: int (bitwise-arithmetic-shift-left
  27. 1 (+ max-depth min-depth (- d))))
  28. (check :: int 0))
  29. (format #t "~d~c trees of depth ~d~c check: ~d~%"
  30. (* iterations 2) #\tab d #\tab
  31. (do ((i :: int 1 (+ 1 i)))
  32. ((> i iterations) check)
  33. (set! check (+ check
  34. ((bottom-up-tree i d):item-check)
  35. ((bottom-up-tree (- i) d):item-check)))))))
  36. (format #t "long lived tree of depth ~d~c check: ~d~%"
  37. max-depth #\tab (long-lived-tree:item-check)))
  38. (define N (string->number (cadr (command-line))))
  39. (test N)