簡體   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