方案消耗BT树,并以字符串列表的形式返回树的元素

ads27

为二进制尝试提供了以下定义

(define-struct leaf ())
;; interpretation: represents a leaf on a BT, a node with no children

(define-struct node (word left right))
;; interpretation: represents a node on a BT with a word, a left and a right 
;; subtree

;; A BinaryTree (BT) is one of 
;; - (make-leaf)
;; - (make-node String BT BT)

设计程序bt-> los,该程序使用BT树并以字符串列表形式返回树的元素。在每个节点上,您的功能应

1.处理左子树

2.在这个节点上处理单词

3.处理正确的子树

;; bt->los: tree -> los 
;; consumes a BT tree and returns the elements of the tree as a list of strings.
(define (bt->los tree)
(cond 
   [(leaf? tree) ""]
   [(node? tree) 
    (append  (bt->los(list (node-left tree)))
             (list (node-word tree))
             (bt->los (list (node-right tree))))]))

我被困在这里。应该错过了一些东西。我们不需要递归吗?

输出应该是这样的,

 (define bt-abc (make-node "b" 
                       (make-node "a" (make-leaf) (make-leaf))
                       (make-node "c" (make-leaf) (make-leaf))))
  (bt->los bt-abc) (cons "a" (cons "b" (cons "c" empty)))
Rptx

您在这里很近。只是几个错误。

(define (bt->los tree)
 (cond 
   [(leaf? tree) empty]
   [(node? tree) 
    (append  (bt->los (node-left tree))
             (list (node-word tree))
             (bt->los (node-right tree)))]))

首先,您要构建一个字符串列表。因为它是一个列表,所以您的基本情况应该是empty""其次,每个节点已经代表一个BT,因此不需要list它。bt->los返回一个列表。通过此简单的更改,它可以按您的测试用例预期的方式工作。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章