我编写从列表构建平衡二叉树的函数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