【发布时间】:2018-08-12 14:54:32
【问题描述】:
data BTree a = Nil | Node a (BTree a) (BTree a) deriving Show
我了解了两种二叉搜索树。一个是完美的,另一个是完整的。
二叉树是完美二叉树,其中所有内部节点都有两个孩子,并且所有叶子都在同一级别。
二叉树是完整的二叉树,如果所有层都被完全填满,除了可能的最后一层并且最后一层的所有键都尽可能离开
isPerfect :: BTree a -> Bool
isPerfect Nil = True
isPerfect (Node x Nil Nil) = True
isPerfect (Node x lt Nil ) = False
isPerfect (Node x Nil rt ) = False
isPerfect (Node x lt rt ) = (&&) (isPerfect lt) (isPerfect rt)
isComplete :: BTree a -> Bool
isComplete Nil = True
isComplete (Node x Nil Nil) = True
isComplete (Node _ lt Nil ) = False
isComplete (Node x Nil rt ) = False
isComplete (Node _ (Node _ Nil Nil) Nil) = True
isComplete (Node x lt rt ) = (&&) (isComplete lt) (isComplete rt)
现在我必须为通用树实现一种数据类型
data GTree a = Leaf a | Branch a [GTree a] deriving (Show)
如何检查这棵树是否完整或完美,是否必须更改定义?
提前致谢
【问题讨论】:
-
isPerfect不检查是否所有叶子都在同一级别。 -
question 的副本,目前没有正确答案。
-
@chi,我不认为是完全重复的。
-
我看到的唯一区别是这里我们使用通用树——也许这足以让它与众不同。 (这个问题也是从
isPerfect和isComplete的错误实现开始的。)
标签: haskell binary-tree