我刚开始学习计划。我试图制作一个程序来寻找三叉树中的一个项目。如果找到则返回true。
这是我到目前为止所得到的:
(define nullnode '())
(define leaf (lambda (x) (eqv? '() x) nullnode (list x nullnode nullnode nullnode)))
(define tritree (list 9 (leaf 1) (leaf 2) (leaf 3)))
; (display tritree) => (9 (1 () () ()) (2 () () ()) (3 () () ()))
(define lookup
(lambda (tr x)
(or (eqv? x (car tr))
(and (list? (cdr tr)) (lookup (cadr tr) x)))))
我想离开(叶子1)并通过(叶子2)。我怎么能这样做?
有没有更好的方法来定义我的查找?
答案 0 :(得分:2)
这是如何在树中搜索的直接实现,这只是我们这次有三个可能的子树:
(define lookup
(lambda (tr x)
(cond ((null? tr) #f)
((equal? (first tr) x) #t) ; don't use eqv?, equal? is more general
(else
(or (lookup (second tr) x)
(lookup (third tr) x)
(lookup (fourth tr) x))))))
或者,不使用cond
(并且更接近您的想法):
(define lookup
(lambda (tr x)
(and (not (null? tr))
(or (equal? (first tr) x)
(lookup (second tr) x)
(lookup (third tr) x)
(lookup (fourth tr) x)))))
并且做注意到您leaf
的实施不正确,为了使上述工作正常,您必须先修复它:
(define leaf
(lambda (x)
(if (null? x)
nullnode
(list x nullnode nullnode nullnode))))
通过示例输入正常工作:
(lookup tritree 3)
=> #t
(lookup tritree 5)
=> #f