【发布时间】:2013-04-15 22:49:03
【问题描述】:
我编写了函数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>
【问题讨论】:
-
你认为树的高度是什么意思?你能定义它吗?这与 insertInTree 的计算结果相匹配吗?
-
我的家庭作业中只有这个定义:二叉树的高度是从根到最深节点的路径长度。例如,具有单个节点的树的高度为 0;具有三个节点且根有两个孩子的树的高度为 1;等等。哦!这个高度计算有问题=((
-
任务是从已排序的列表中创建树吗?您的递归
insertInTree很好。你可以制作foldTree = foldr insertInTree Leaf。除了代码审查类型的东西,你能澄清一下你在问什么吗? -
我现在不确定 insertTree 函数:计算高度是否正确?我的意思是节点内(h2+1)节点(h1+1)?以及如何将 insertTree 作为一对管道函数?
-
计算高度对于平衡来说是必要的。您已经保存了每个节点的高度,所以
heightTree是 O(1)。
标签: haskell recursion binary-tree fold higher-order-functions