2
鑑於以下數據結構,創建該給定GenTree
的功能,把它變成BinTree
:功能把一個GenTree到二叉樹
- 每個爲了
NodeG
在二叉樹一個NodeB
節點匹配; NodeB
的左邊兒子匹配NodeG
的第一個兒子;- 的
NodeB
右子是如下NodeG
(這意味着,爲了NodeG
的父母的童裝之間的下一個節點)
視覺示例(GenTree
左,BinTree
右)
1 1
/| | \ /\
2 3 4 5 2 E
/|\ /\
6 7 8 E 3
/\
E 4
/\
6 5
/\
E 7
/\
E 8
data GenTree a = EmptyG | NodeG a [GenTree a]
deriving (Show)
data BinTree a = EmptyB | NodeB (BinTree a) a (BinTree a)
deriving (Show)
。我無法弄清楚如何使主函數的輔助函數(aux)工作。
g2b :: (GenTree a) -> (BinTree a)
g2b EmptyG = EmptyB
g2b (NodeG x ts) = NodeB (aux ts) x EmptyB
aux :: [GenTree a] -> (BinTree a)
aux [] = EmptyB
aux (NodeG x xs) : xss = NodeB (aux xs) x (aux xss) ((NodeG x xs) xss)
的最後一行代碼是不工作,和一個我不明白
在我看來,你的問題有點不確定。 「GenTree」比「BinTree」更大,因爲他們有更多的東西:NodeG有很多孩子,而NodeB只有兩個孩子。當你遇到不適合NodeB的'NodeG'時,你的代碼應該做什麼?你需要想出一些扁平化策略 –
在問題的深入解釋中增加了更多內容,並且提供了函數應該如何工作的可視化示例 –