到目前为止,我有这段代码:
data BinaryTree a = Null | Node a (BinaryTree a) (BinaryTree a)
treeLeaves :: BinaryTree a -> [a]
treeLeaves tree = case tree of
Null -> []
Node v t1 t2 -> [] ++ treeLeaves t1 ++ treeLeaves t2
我不确定我做错了什么。它输出一个空列表。
现在你错过了重要的步骤,即将叶子添加到你的列表中,这就是为什么你总是得到一个空列表。正如Zeta评论的那样,这种[] ++ treeLeaves t1 ++ treeLeaves t2
最终将落在Null
分支中并变得[] ++ [] ++ ... ++ []
。
你知道你已经到达了一片叶子,当BinaryTree
Node v Null Null
.所以你也需要为这种情况写一个分支:
treeLeaves :: BinaryTree a -> [a]
treeLeaves tree = case tree of
Null -> []
Node v Null Null -> v:[]
Node _ t1 t2 -> treeLeaves t1 ++ treeLeaves t2
正如 Igor 评论的那样,您可以使用_
而不是最后一行的v
,因为您没有使用该节点中的元素(因为它不是叶子)。