sicp每日一题[2.66]

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
posted @   再思即可  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示