#lang racket (require htdp/testing) (define Tix '((Amy 2 3 41 42 50) (Bea 3 4 50 51 52))) (define Win '( 1 3 41 51 52 )) (define (matches T W) (length (filter (lambda (x) (member x T)) W))) ;; a binary search tree... (define BT2 '( 42 ( 20 (12 () ()) (21 () (35 (25 () ()) (39 () ())) )) (100 () (211 () ()) ) ) ) (define B42 '(42 (20 (12 () ()) (21 () (35 (25 () ()) ()))) (100 () (211 () ())))) (define B4 '(42 () (60 () (100 () ())))) ;; in-line printing of a BST (define (pp BST) (if (null? BST) (begin (display '())) (let* ((rt (first BST)) (L (second BST)) (R (third BST))) (begin (display rt) (pp L) (pp R))))) ;; in-order traversal of a BST ;; input: a BST ;; output: a list of the nodes of BST, in order (define (inorder BST) (if (null? BST) '() (let* ((rt (first BST)) (L (second BST)) (R (third BST))) (append (inorder L) (list rt) (inorder R))))) ;; a function that prints the top-level structure of a BST (define (my-print BT) (if (null? BT) "empty tree!" (let* ([ root (first BT) ] [ LEFT (second BT) ] [ RIGHT (third BT) ]) (begin ;; good for debugging (display "root: ") (pretty-print root) (display "LEFT: ") (pretty-print LEFT) (display "RIGHT: ") (pretty-print RIGHT) "done!") ))) ;; (my-print BT2) ;(check-expect (insert 42 '(20 () ())) '(20 () (42 () ()))) ;(check-expect (insert 42 '(100 () ())) '(100 (42 () ()) ())) ;; finding the max ;; not well commented...! (define (find-max BT) (let* (( root (first BT) ) ( LEFT (second BT) ) ( RIGHT (third BT) )) (cond ((null? RIGHT) root) ( else (find-max RIGHT) ) ))) (check-expect (find-max BT2) 211) ;; find! ;; ditto! (define (find n BT) (if (null? BT) #f (let* (( root (first BT) ) ;; else this ( LEFT (second BT) ) ( RIGHT (third BT) )) (cond ((equal? n root) #t) ((< n root) (find n LEFT)) ( else (find n RIGHT))) ))) (check-expect (find 33 BT2) #f) (check-expect (find 20 BT2) #t) (check-expect (find 211 BT2) #t) ;; insert! ;; input: a node, n, and a BST, BT ;; output: a new BST, similar to BT, but with n in it ;; if n is already there, the result won't change ;; O(height); O(logN) if the tree is (relatively) balanced (define (insert n BT) (if (null? BT) ;; if there are no nodes, (list n '() '()) ;; return a new tree with n at root (let* ( ;; otherwise... ( root (first BT) ) ;; a bit more verbose ( LEFT (second BT) ) ;; rt, L, R are 100% OK! ( RIGHT (third BT) ) ) (cond ((equal? n root) BT) ;; no change! ;; insert on left: ((< n root) (list root (insert n LEFT) RIGHT)) ;; insert on right: ( else (list root LEFT (insert n RIGHT))) )))) (check-expect (insert 42 BT2) BT2) (check-expect (insert 42 '(20 () ())) '(20 () (42 () ()))) (check-expect (insert 42 '(100 () ())) '(100 (42 () ()) ())) (generate-report)