Haskell中的最大树深度 [英] Maximum tree depth in Haskell
本文介绍了Haskell中的最大树深度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我给了这个类型定义:
I am given this type definition:
data Tree = Leaf Char | Branch2 Char Tree Tree | Branch3 Char Tree Tree Tree
如何编写一个方法给我树的最大路径长度(计算路径中的节点数)?
How can I write a method that gives me the maximum path length of the tree (count the nodes in the path)?
推荐答案
你会想写一个递归函数来做到这一点。对于每个 Tree
构造函数,您需要在函数中使用不同的大小写。首先,你知道任何 Leaf
的深度都是 1
,所以
You would want to write a recursive function to do this. For each Tree
constructor, you'll need a different case in your function. To start with, you know that the depth of any Leaf
is 1
, so
maxDepth :: Tree -> Int
maxDepth (Leaf _) = 1
maxDepth (Branch2 c left right) = maximum [???]
maxDepth (Branch3 c left center right) = maximum [???]
我会让你完成剩下的功能。你也可以通过几种不同的方式来实现(比如使用 max
而不是最大
)。
I'll let you finish the rest of the function. You could do it a few different ways as well (such as using max
instead of maximum
).
这篇关于Haskell中的最大树深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文