fork download
  1. ; balanced binary search trees
  2.  
  3. (define (insert lt? x tree)
  4. (cond ((null? tree)
  5. (list x (list) (list)))
  6. ((lt? x (car tree))
  7. (list (car tree) (insert lt? x (cadr tree)) (caddr tree)))
  8. ((lt? (car tree) x)
  9. (list (car tree) (cadr tree) (insert lt? x (caddr tree))))
  10. (else tree)))
  11.  
  12. (define (member? lt? x tree)
  13. (cond ((null? tree) #f)
  14. ((lt? x (car tree)) (member? lt? x (cadr tree)))
  15. ((lt? (car tree) x) (member? lt? x (caddr tree)))
  16. (else #t)))
  17.  
  18. (define unbal-tree (insert < 4 (insert < 6 (insert < 0 (insert < 7
  19. (insert < 1 (insert < 5 (insert < 2 (insert < 3 (list))))))))))
  20.  
  21. (define bal-tree (insert < 0 (insert < 6 (insert < 4 (insert < 2
  22. (insert < 1 (insert < 5 (insert < 3 (list)))))))))
  23.  
  24. (define (depth tree)
  25. (if (null? tree) 0
  26. (+ 1 (max (depth (cadr tree))
  27. (depth (caddr tree))))))
  28.  
  29. (define (balanced? tree)
  30. (if (null? tree) #t
  31. (and (= (depth (cadr tree))
  32. (depth (caddr tree)))
  33. (balanced? (cadr tree))
  34. (balanced? (caddr tree)))))
  35.  
  36. (display (balanced? unbal-tree)) (newline)
  37. (display (balanced? bal-tree)) (newline)
  38.  
  39. (define (balanced? tree)
  40. (or (null? tree)
  41. (and (null? (cadr tree)) (null? (caddr tree)))
  42. (and (not (null? (cadr tree))) (not (null? (caddr tree)))
  43. (balanced? (cadr tree)) (balanced? (caddr tree)))))
  44.  
  45. (display (balanced? unbal-tree)) (newline)
  46. (display (balanced? bal-tree)) (newline)
  47.  
Success #stdin #stdout 0.02s 42848KB
stdin
Standard input is empty
stdout
#f
#t
#f
#t