; balanced binary search trees
(define (insert lt? x tree)
(cond ((null? tree)
(list x (list) (list)))
((lt? x (car tree))
(list (car tree) (insert lt? x (cadr tree)) (caddr tree)))
((lt? (car tree) x)
(list (car tree) (cadr tree) (insert lt? x (caddr tree))))
(else tree)))
(define (member? lt? x tree)
(cond ((null? tree) #f)
((lt? x (car tree)) (member? lt? x (cadr tree)))
((lt? (car tree) x) (member? lt? x (caddr tree)))
(else #t)))
(define unbal-tree (insert < 4 (insert < 6 (insert < 0 (insert < 7
(insert < 1 (insert < 5 (insert < 2 (insert < 3 (list))))))))))
(define bal-tree (insert < 0 (insert < 6 (insert < 4 (insert < 2
(insert < 1 (insert < 5 (insert < 3 (list)))))))))
(define (depth tree)
(if (null? tree) 0
(+ 1 (max (depth (cadr tree))
(depth (caddr tree))))))
(define (balanced? tree)
(if (null? tree) #t
(and (= (depth (cadr tree))
(depth (caddr tree)))
(balanced? (cadr tree))
(balanced? (caddr tree)))))
(display (balanced? unbal-tree)) (newline)
(display (balanced? bal-tree)) (newline)
(define (balanced? tree)
(or (null? tree)
(and (null? (cadr tree)) (null? (caddr tree)))
(and (not (null? (cadr tree))) (not (null? (caddr tree)))
(balanced? (cadr tree)) (balanced? (caddr tree)))))
(display (balanced? unbal-tree)) (newline)
(display (balanced? bal-tree)) (newline)