Exercise 2.66
Implement the lookup procedure for the case where the set of records is structured as a binary tree, ordered by the numerical values of the keys.
這道題還是挺簡單的,由於是有序的二叉樹,所以可以先比較根與要查詢的數字的大小,如果相等就查到了;如果根小於要查詢的數,則遞迴呼叫判斷右子樹中是否包含這個數; 如果根大於要查詢的數,則去左子樹去查即可。
(define (lookup given-key set-of-records)
(if (null? set-of-records)
false
(let ((root (entry set-of-records)))
(cond ((= given-key root) true)
((< given-key root) (lookup given-key (left-branch set-of-records)))
(else (lookup given-key (right-branch set-of-records)))))))
(define test (list->tree (list 1 2 3 4 5 6 7 8 9)))
(lookup 7 test)
(lookup 10 test)
; 結果如下
#t
#f