繁体   English   中英

判断树是否完整时,“方程具有不同数量的参数”

[英]'Equations have different numbers of arguments' when deciding whether a tree is complete or not

我试图使用一个函数来确定二叉树是否完整,但是编译器一直告诉我“等式具有不同数量的参数”。

猜测错误是关于语法的,但是我只是找不到正确的格式。

data BinaryTree a = Leaf a | Node (BinaryTree a) a (BinaryTree a)

...

decideComplete :: BinaryTree Int -> Bool
decideComplete (Node l _ r) = (decideComplete l) && (decideComplete r)
decideComplete Leaf v = True

您的decideComplete函数采用decideComplete BinaryTree Int (也许要将其概括为BinaryTree a )。 Leaf不是BinaryTree a ,它是一个带参数的数据构造函数,因此您应该添加方括号,例如:

decideComplete :: BinaryTree a -> Bool
decideComplete (Node l _ r) = (decideComplete l) && (decideComplete r)
decideComplete (Leaf v) = True

话虽这么说,您的函数将在此处为所有树生成True (当然,除非树具有无限数量的节点,但是在那种情况下,它只会陷入无限循环或耗尽内存)。 确实:对于所有Leaf ,它将返回True ,而对于Node l _ r ,将在lr上都给定decideComplete返回True ,但是这不可能返回False ,因为最终子树将是Leaf s,因此该节点将为True ,因此通过归纳,所有BinaryTree都将为True

为了检查一棵二叉树是否完整,除最后一个树外的所有层都应满。 最后一级应包含最左侧的节点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM