我想获得树的最大值
我有这个:
define (dato-tree nodo)
(first nodo))
(define (left-tree nodo)
(first (rest nodo)))
(define (right-tree nodo)
(first (rest (rest nodo))))
(define maximum
(lambda (arbol)
(if (eqv? (right-tree arbol) #f)
arbol
(maximum (right-tree arbol)))))
并运行它:
(define tree (list 5 (list 2 (list 1 empty empty) empty) (list 7 empty empty)))
(maximum tree)
给了我这个错误:
rest: expects a non-empty list; given: empty
怎么可能?
答案 0 :(得分:0)
如果树是上一个问题中建议的已排序二叉树,则只需考虑正确的分支并找到最后一个节点的值:
(define (maximum arbol (m #f))
(if (empty? arbol)
m
(maximum (right-tree arbol) (dato-tree arbol))))
然后
> (maximum tree)
7
您甚至可以指定要为空树返回的值:
> (maximum empty)
#f
> (maximum empty 'empty)
'empty
> (maximum empty empty)
'()
否则我会选择:
(define (cons2 atom lst)
(if atom (cons atom lst) lst))
(define (maximum arbol)
(if (empty? arbol)
#f
(apply max
(cons2 (maximum (left-tree arbol))
(cons2 (maximum (right-tree arbol))
(list (dato-tree arbol)))))))
其中cons2
是仅在不是#f
的情况下才包含原子的过程:
> (cons2 1 '(2))
'(1 2)
> (cons2 #f '(2))
'(2)
并在过程maximum
中派上用场,以防止在子树的最大值为empty
时进行测试:
> (maximum tree)
7
> (maximum empty)
#f