我編寫從列表構建平衡二叉樹的函數foldTree
。 我必須使用foldr
,它沒問題,我用它,但我讓insertInTree
函數遞歸=(現在我只知道這種方式走過樹=))。使用foldr構建平衡二叉樹
UPDATE:iam不知道函數insertTree
:是否正確計算遞歸的高度? =((在這裏需要一些幫助
是否有可能寫insertInTree
無遞歸(一些與until/iterate/unfoldr
)或使foldTree
功能,無需輔助功能=>莫名其妙短
這是我下面的嘗試:?
data Tree a = Leaf
| Node Integer (Tree a) a (Tree a)
deriving (Show, Eq)
foldTree :: [a] -> Tree a
foldTree = foldr (\x tree -> insertInTree x tree) Leaf
insertInTree :: a -> Tree a -> Tree a
insertInTree x Leaf = Node 0 (Leaf) x (Leaf)
insertInTree x (Node n t1 val t2) = if h1 < h2
then Node (h2+1) (insertInTree x t1) val t2
else Node (h1+1) t1 val (insertInTree x t2)
where h1 = heightTree t1
h2 = heightTree t2
heightTree :: Tree a -> Integer
heightTree Leaf = 0
heightTree (Node n t1 val t2) = n
輸出:當兩個子樹的高度EQU
*Main> foldTree "ABCDEFGHIJ"
Node 3 (Node 2 (Node 0 Leaf 'B' Leaf) 'G' (Node 1 Leaf 'F' (Node 0 Leaf 'C' Leaf))) 'J' (Node 2 (Node 1 Leaf 'D' (Node 0 Leaf 'A' Leaf)) 'I' (Node 1 Leaf 'H' (Node 0 Leaf 'E' Leaf)))
*Main>
你怎麼看樹手段的高度?你能定義它嗎?這與insertInTree計算的結果相符嗎? – 2013-04-22 21:56:37
我從我的作業任務中只有這個定義:二叉樹的高度**是從根到最深節點的路徑的長度。例如,具有單個節點的樹的高度爲0;具有三個節點,其根具有兩個子節點的樹的高度爲1;等等。哦!這個高度有些不正確計算=(( – 2013-04-22 22:56:11
是從已經排序的列表創建樹的任務嗎?你的遞歸'insertInTree'沒問題,你可以使'foldTree = foldr insertInTree Leaf'。除了代碼審查類型的東西外,你能否澄清你所問的內容? – jberryman 2013-04-23 04:19:23