Guest User

Untitled

a guest
Apr 19th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. (A 2 B 1 F 0 C 2 D 0 E 0)
  2.  
  3. (A 2 B 1 F 0 C 2 D 0 E 0)
  4.  
  5. (defun tlist->tree (tlist)
  6. "Transforms a tree represented as a kind of plist into a tree.
  7. A tree like:
  8. A
  9. /
  10. B C
  11. / /
  12. F D E
  13. would have a tlist representation of (A 2 B 1 F 0 C 2 D 0 E 0).
  14. The tree representation would be (A (B (F)) (C (D) (E)))"
  15. (let (tree)
  16. (push (pop tlist) tree)
  17. (dotimes (i (pop tlist))
  18. (multiple-value-bind (subnode rest-tlist) (tlist->tree tlist)
  19. (push subnode tree)
  20. (setf tlist rest-tlist)))
  21. (values (nreverse tree) tlist)))
  22.  
  23. (defun depth-rec (tree)
  24. (labels ((depth-rec-aux (depth) ; self-recursive function
  25. (if (null tree) ; no more nodes
  26. depth ; -> return the current depth
  27. (let ((n (second tree))) ; number of subnodes
  28. (pop tree) (pop tree) ; remove the current node
  29. (case n
  30. (0 (1+ depth)) ; no subnode, 1+depth
  31. (1 (depth-rec-aux (1+ depth))) ; one subnode, its depth+1
  32. (2 (max (depth-rec-aux (1+ depth)) ; two subnodes, their max
  33. (depth-rec-aux (1+ depth)))))))))
  34. (depth-rec-aux 0))) ; start depth is 0
  35.  
  36. (defun depth-rec (tree &aux (max 0))
  37. (labels ((depth-rec-aux (depth)
  38. (when tree
  39. (pop tree)
  40. (let ((n (pop tree)))
  41. (if (zerop n)
  42. (setf max (max max (1+ depth)))
  43. (loop repeat n do (depth-rec-aux (1+ depth))))))))
  44. (depth-rec-aux 0))
  45. max)
  46.  
  47. (defun depth (tree) (1+ (apply #'max -1 (mapcar #'depth (rest tree)))))
  48.  
  49. (defun oddtree-height (oddtree)
  50. (suboddtree-height oddtree
  51. #'(lambda (h remainder)
  52. (if (null remainder) h nil))))
  53.  
  54. (defun suboddtree-height (oddtree c)
  55. (max-height-of-suboddtrees (cadr oddtree)
  56. 0
  57. (cddr oddtree)
  58. #'(lambda (h remainder)
  59. (funcall c (+ h 1) remainder))))
  60.  
  61. (defun max-height-of-suboddtrees (n best oddtree c)
  62. (if (= n 0)
  63. (funcall c best oddtree)
  64. (suboddtree-height oddtree
  65. #'(lambda (h remainder)
  66. (max-height-of-suboddtrees (- n 1) (max best h) remainder c)))))
Add Comment
Please, Sign In to add comment