dictionary - 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)
解决方案
推荐阅读
- python-3.x - 如何使用 groupby 对相似值进行分组
- android - 如何在 RTL 中使用 CountryCodePicker?
- python - 强制执行唯一约束 SQLALchemy 关系
- netsuite - 如果我们使用 SuiteBilling,如何跟踪配置过程?
- python - 如何使用 DeepFace.detectFace() 实际检测图像中的人脸?
- python - 如何将安全规则从 Python 的服务器客户端库集成到 Firestore 客户端?
- r - Rshiny 中的错误:“没有默认值的参数丢失”
- r - 如何将字符串日期时间列转换为 R 中的日期时间列?
- css - 从 Google 表格列数据创建 CSS 类
- ios - React-native unrecognized font family error