(define make-empty-tree (lambda () '())) (define make-nonempty-tree (lambda (root left-subtree right-subtree) (list root left-subtree right-subtree))) (define example-tree (make-nonempty-tree 191 (make-nonempty-tree 157 (make-empty-tree) (make-empty-tree)) (make-nonempty-tree 202 (make-nonempty-tree 200 (make-empty-tree) (make-empty-tree)) (make-empty-tree)))) (define empty-tree? null?) (define root car) (define left-subtree cadr) (define right-subtree caddr) (define in? (lambda (value tree) (cond ((empty-tree? tree) #f) ((= value (root tree)) #t) ((< value (root tree)) (in? value (left-subtree tree))) (else ; the value must be greater than the root (in? value (right-subtree tree)))))) (define tree-maximum (lambda (tree) ; tree must be non-empty (cond ((empty-tree? tree) (error "this doesn't make sense -- there is no element, so how could one be largest?")) ((empty-tree? (right-subtree tree)) (root tree)) (else (tree-maximum (right-subtree tree)))))) (define inorder (lambda (tree) (if (empty-tree? tree) '() (append (inorder (left-subtree tree)) (cons (root tree) (inorder (right-subtree tree))))))) (define list-head (lambda (lst n) (if (= n 0) '() (cons (car lst) (list-head (cdr lst) (- n 1)))))) (define sl->mhbst ; sorted list -> minimum height binary search tree (lambda (sl) (if (null? sl) (make-empty-tree) (let ((middle-position (quotient (length sl) 2))) (make-nonempty-tree (list-ref sl middle-position) (sl->mhbst (list-head sl middle-position)) (sl->mhbst (list-tail sl (+ 1 middle-position)))))))) (define height (lambda (tree) (cond ((Empty-tree? tree) -1) (else (+ (max (height (right-subtree tree)) (height (left-subtree tree))) 1)))))