【问题标题】:How to return tree's leaves in a list in Haskell如何在 Haskell 的列表中返回树叶
【发布时间】:2017-10-04 12:29:11
【问题描述】:

到目前为止我有这个代码:

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

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

【问题讨论】:

  • 在用 Haskell 写之前,请先解释一下你自己会怎么做?您希望程序采取哪些步骤来归还叶子?
  • [] ++ x ++ yx ++ ytreeLeaves 什么时候会返回 [] 以外的其他内容?
  • 来自Node v t1 t2v 参数未在实现中使用。嗯,也许我们可以用它做点什么或使用_ 而不是分心...

标签: list haskell tree binary-tree


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-19
    • 2022-01-25
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    相关资源
    最近更新 更多