我编写了foldTree
从列表构建平衡二叉树的函数。我必须使用foldr
,没关系,我用过,但我使insertInTree
函数递归=(现在我只知道这种方式可以穿过树=))。
更新:我不确定功能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
输出:
*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>