我正在尝试为 DrRacket 中的树编写折叠命令,只知道如何编写二叉树。有什么建议吗?它应该采用f
诸如+,-等的功能。并折叠所有给定的数据,但不是通过展平树。
到目前为止,这是我想出的:
(define (bt-constr int left right) (list int left right))
(define (bt-val tree) (car tree))
(define (bt-left tree) (cadr tree))
(define (bt-right tree) (caddr tree))
(define (bt-fold f int tree)
(if (null? tree) int
(f (bt-val tree) (f (bt-fold f int (bt-left tree)) (bt-fold f int (bt-right tree))))))
提前致谢!