リストから平衡二分木を構築する関数foldTree
を書く。 私はfoldr
を使用しなければなりません。それは大丈夫です、私はそれを使用しましたが、私はinsertInTree
関数を再帰的にします=(今のところ私は木を通り抜けるこの方法しか知っていません))。foldrで平衡した二分木を構築する
更新日:iamは関数についてはわかりませんinsertTree
:再帰の高さを正しく計算していますか? 。=((それはuntil/iterate/unfoldr
と(何か)は、再帰なしinsertInTree
を書き込むことができる
ここにいくつかの助けを必要とするか、ヘルパー関数なし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
出力:
*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が計算するものと一致しますか? –
私は自分の宿題からこの定義だけを持っています。 **高さ**は、ルートから最も深いノードまでのパスの長さです。たとえば、1つのノードを持つツリーの高さは0です。 ルートが2つの子を持つ3つのノードを持つツリーの高さは1です。等々。ああ!何か間違っているこの高さコンピューティング=(( –
既に順序付けされたリストからツリーを作成するタスクはありますか?再帰的な 'insertInTree'は問題ありません)' foldTree = foldr insertInTree Leaf'を行うことができます。あなたは、コードレビュータイプのもののほかに何を求めているのかを明確にすることができますか? – jberryman