为您提供以下二进制尝试的定义
(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)))
答案 0 :(得分:1)
你离这儿很近。只是几个错误。
(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
返回
一个列表。通过这些简单的更改,它可以按预期的方式运行测试用例。