我创建了一个这样的inorder函数:
(define inorder
(λ (tree)
(unless(empty? (node-left tree)) (inorder(node-left tree)))
(print (node-x tree))
(unless(empty? (node-right tree)) (inorder(node-right tree)))
)
)
如何创建包含所有node-x树元素的列表,而不是打印它们。我需要我的inorder函数来返回这些元素的列表。 我尝试使用辅助功能,但它不起作用......
答案 0 :(得分:1)
您需要设想(inorder (node-left tree))
和(inorder (node-right tree))
都会返回一个列表。你如何利用这些和这个元素来得出最终结果?
空树的结果将是一个空列表。这应该是你的基本情况:
因此你需要它看起来像这样:
(define (inorder tree)
(if (empty? tree)
'()
(append (inorder (node-left tree))
(list (node-x tree))
(inorder (node-right tree)))))
一个更好的版本,不会对每个级别使用append
,但是对于每个元素,将元素放在其中的正确位置是这样的:
(define (tree->list tree)
(let tree->list ((n tree) (acc '()))
(if (empty? n)
acc
(tree->list
(node-left n)
(cons (node-x n)
(tree->list (node-right n) acc))))))
起初稍微难以理解,但在较大的树上表现更好。
答案 1 :(得分:0)
第一步是让inorder
返回列表。假设您需要一个平面列表,这意味着我们可以将inorder
返回的列表作为左子树,当前节点和右侧子树,并附加每个列表以生成一个从二叉树最左侧到右侧的节点值的平面列表。
(define inorder
(λ (tree)
(append (inorder(node-left tree))
(list (node-x tree))
(inorder(node-right tree)))))
请注意,我为当前节点创建了长度为1的列表,同时子树将返回列表。这个骨架应该足以让你了解递归如何解决这个问题。
现在我们得到一个空树:如果我们有一个空树,那么我们应该返回一个空列表,因为它没有要添加的元素。使用if
:
(define inorder
(λ (tree)
(if (empty? tree)
'()
(append (inorder(node-left tree))
(list (node-x tree))
(inorder(node-right tree))))))