bintrees.nim 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- nim -*-
  2. import os, strutils
  3. type
  4. PNode = ref TNode
  5. TNode {.final, acyclic.} = object
  6. left, right: PNode
  7. item: int
  8. proc checkTree(node: PNode): int =
  9. result = node.item
  10. if node.left != nil:
  11. inc result, checkTree(node.left) - checkTree(node.right)
  12. proc makeTreeAux(item, depth: int): PNode =
  13. new(result)
  14. result.item = item
  15. if depth > 0:
  16. result.left = makeTreeAux(2 * item - 1, depth - 1)
  17. result.right = makeTreeAux(2 * item, depth - 1)
  18. proc makeTree(item, depth: int): PNode =
  19. #GC_disable()
  20. result = makeTreeAux(item, depth)
  21. #GC_enable()
  22. proc main =
  23. var n = parseInt(paramStr(1))
  24. const minDepth = 4
  25. var maxDepth = if minDepth+2 > n: minDepth+2 else: n
  26. var stretchDepth = maxDepth + 1
  27. echo("stretch tree of depth ", stretchDepth, "\t check: ", checkTree(
  28. makeTree(0, stretchDepth)))
  29. var longLivedTree = makeTree(0, maxDepth)
  30. var iterations = 1 shl maxDepth
  31. for depth in countup (minDepth, stretchDepth-1, 2):
  32. var check = 0
  33. for i in 1..iterations:
  34. check += checkTree(makeTree(i, depth)) + checkTree(makeTree(-i, depth))
  35. echo(iterations*2, "\t trees of depth ", depth, "\t check: ", check)
  36. iterations = iterations div 4
  37. echo("long lived tree of depth ", maxDepth, "\t check: ",
  38. longLivedTree.checkTree)
  39. echo GC_getstatistics()
  40. main()