Scheme 查找空值的递归
我试图在树中找到最大值,但是我在理解它的递归部分时遇到了困难 到目前为止我所拥有的Scheme 查找空值的递归,scheme,racket,Scheme,Racket,我试图在树中找到最大值,但是我在理解它的递归部分时遇到了困难 到目前为止我所拥有的 (define mytree '(10 (5(4(2 ()()) (22()())) (21(15()()) (23 ()()))) (11(6()())(13()())))) (define (leaf mytree) (and(null?(cadr mytree)) (null? (caddr mytree)))) (define (maxval mytree) (if (null? mytr
(define mytree '(10 (5(4(2 ()()) (22()())) (21(15()()) (23 ()()))) (11(6()())(13()()))))
(define (leaf mytree)
(and(null?(cadr mytree)) (null? (caddr mytree))))
(define (maxval mytree)
(if (null? mytree)
mytree
(max (leaf(maxval (cadr mytree))) (leaf(maxval (caddr mytree))))))
(maxval mytree)
我试图让leaf函数遍历树中的每个数字,直到找到最下面的数字,在那里它将找到最大的值。简短版本:您需要一个数据定义和测试用例 您的数据定义应该是
;; a binary tree is either:
;; -- <you fill in this part>, or
;; -- <you fill in this part too>
;;二叉树是:
;; -- , 或
;; --
然后,您需要测试用例
- 为数据定义的两种情况编写一个测试用例
(一般来说,步进器可能会有所帮助,但在这种情况下,我认为问题会更早出现。)简短版本:您需要数据定义和测试用例 您的数据定义应该是
;; a binary tree is either:
;; -- <you fill in this part>, or
;; -- <you fill in this part too>
;;二叉树是:
;; -- , 或
;; --
然后,您需要测试用例
- 为数据定义的两种情况编写一个测试用例
- 缩进代码、对齐子树、添加空格
- 结尾带有
的名称谓词?
- 使用
而不是tree
mytree
- 定义抽象(
,left child
,而不是cadr汤)right child
(define mytree
'(10 (5 (4 (2 () ())
(22 () ()))
(21 (15 ()())
(23 ()())))
(11 (6 () ())
(13 () ()))))
(define (tree-value tree)
(car tree))
(define (left-child tree)
(cadr tree))
(define (right-child tree)
(caddr tree))
(define (leaf? tree)
(and (null? (left-child tree)
(null? (right-child tree))))
(define (maxval tree)
(if (null? tree)
'()
(max (leaf? (maxval (left-child tree)))
(leaf? (maxval (right-child tree))))))
递归算法
树的最大值(最大值树)
是以下各项中的最大值:
(树值树)
(maxvalue(左子树))
(maxvalue(右子树))
- 为什么
的结果被赋予leaf?
max
- 为什么不检查以当前树为根的值
- 缩进代码、对齐子树、添加空格
- 结尾带有
的名称谓词?
- 使用
而不是tree
mytree
- 定义抽象(
,left child
,而不是cadr汤)right child
(define mytree
'(10 (5 (4 (2 () ())
(22 () ()))
(21 (15 ()())
(23 ()())))
(11 (6 () ())
(13 () ()))))
(define (tree-value tree)
(car tree))
(define (left-child tree)
(cadr tree))
(define (right-child tree)
(caddr tree))
(define (leaf? tree)
(and (null? (left-child tree)
(null? (right-child tree))))
(define (maxval tree)
(if (null? tree)
'()
(max (leaf? (maxval (left-child tree)))
(leaf? (maxval (right-child tree))))))
递归算法
树的最大值(最大值树)
是以下各项中的最大值:
(树值树)
(maxvalue(左子树))
(maxvalue(右子树))
- 为什么
的结果被赋予leaf?
max
- 为什么不检查以当前树为根的值