首页 > 解决方案 > Haskell:更新二叉树

问题描述

我想实现一个映射函数mapLeaves,该函数仅映射到二叉树中的叶子。并返回一个更新的树。

data Tree = TNode Int [Tree] | Tleaf Int

    
         -1
        /   \
      -5     10
      / \   
    -4  30  
    / \
   13  17

t = TNode (-1) [TNode (-5)  [  TNode (-4) [ Tleaf 13, Tleaf 17] ,  Tleaf 30 ] ,Tleaf 10 ]

getListLeaves (Tleaf x)= [x]
getListLeaves (TNode x [Tleaf y])=[y]
getListLeaves (TNode x (y:ys))=  (getListLeaves y) ++ (getListLeaves (TNode x ys)) 

mapLeaves f tree = map (f) (getListLeaves tree)

mapLeaves (+3) t 得到答案 [16,20,33,13]

这是我停下来的地方,我怎样才能把这个列表变成二叉树,就像上面显示的 t 一样,它的叶子得到了更新,但节点仍然存在。提前致谢。

编辑:为什么这是有效的,

sumLeaves :: Tree -> Int
sumLeaves (Tleaf x)=x
sumLeaves (TNode n xs)=sum (map sumLeaves xs)

但是当我将 sum 更改为 TNode n 时它不起作用,

sumLeaves :: Tree -> Int
sumLeaves (Tleaf x)=x
sumLeaves (TNode n xs)=TNode n (map sumLeaves xs)

这也是我卡住的地方,

mapLeaves :: (Int -> Int) -> Tree -> Tree
mapLeaves f (Tleaf x) = Tleaf (f x)
mapLeaves f (TNode x cs)=TNode x  (map mapLeaves f cs)

标签: dictionaryhaskellbinary-tree

解决方案



推荐阅读