繁体   English   中英

如何在Haskell的列表中返回树的叶子

[英]How to return tree's leaves in a list in Haskell

到目前为止,我有以下代码:

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

我不确定自己在做什么错。 它输出一个空列表。

现在,您错过了重要的一步,即将叶子添加到列表中,这就是为什么您总是得到一个空列表的原因。 [] ++ treeLeaves t1 ++ treeLeaves t2[] ++ treeLeaves t1 ++ treeLeaves t2最终将落在Null分支中,并成为[] ++ [] ++ ... ++ []

您知道当BinaryTreeNode 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 ,因为您没有在该节点中使用该元素(因为它不是叶子)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM