2017-10-04 60 views
0

在列表樹的落葉歸我到目前爲止這樣的代碼:如何在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 

我不知道我做錯了。它輸出一個空的列表。

+4

在寫入Haskell之前,請先解釋一下你自己會怎麼做?您希望程序採取哪些步驟來返回樹葉? –

+7

'[] ++ x ++ y'是'x ++ y'。 'treeLeaves'在什麼時候返回別的不是'[]'? – Zeta

+5

來自'Node v t1 t2'的'v'參數在實現中不使用。嗯,也許我們可以用它做點什麼,或者用'_'代替不要分心...... –

回答

5

現在你錯過了將葉子添加到列表中的重要步驟,這就是爲什麼你總是得到一個空列表。當Zeta評論時,[] ++ 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 

正如伊戈爾評論,你可以在最後一行,因爲你沒有使用元素在該節點使用_代替v(因爲它不是一個葉)。