【问题标题】:How to check whether a binary tree has the heap property?如何检查二叉树是否具有堆属性?
【发布时间】:2013-05-19 21:03:52
【问题描述】:

给定一棵二叉树,我想检查它是否具有堆属性,例如如果B是A的子节点那么key(A)>=key(B):

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

我的功能开始如下:

isHeap :: Tree a -> Bool

isHeap Leaf = True

isHeap (Node a left right) = if (Node a)>= isHeap(left) && (Node a)>= isHeap(right) then True else False

这是错误的,因为 GHCI 告诉它无法匹配预期类型 Tree a->Tree a->Tree a 与实际类型 Bool?

我知道我错了,但我认为它在正确的轨道上。有什么想法吗?

【问题讨论】:

  • 旁注:如果你发现自己写了if Condition then True else Falseif Condition then False else True,你可以简单地写Conditionnot Condition

标签: haskell


【解决方案1】:

你有几个问题。 首先,要使用>=,你需要添加Ord约束,所以isHeap的类型应该是

isHeap :: Ord a => Tree a -> Bool

其次,除了知道子节点是否满足堆属性之外,您还需要子节点的值。您可以匹配子节点类型,例如

isHeap :: Ord a => Tree a -> Bool
isHeap Leaf = True

isHeap (Node a Leaf Leaf) = True
isHeap (Node a c1@(Node b _ _) Leaf) = ...
isHeap (Node a Leaf c2@(Node b _ _)) = ...
isHeap (Node a c1@(Node b _ _) c2@(Node c _ _)) = ...

在最后一个模式中,bc 是子节点的值,您需要将其与父节点的值 (a) 进行比较,而 c1c2 是节点本身。

要回答有关您的错误的问题,Node 构造函数是类型的函数

Node :: a -> Tree a -> Tree a -> Tree a

所以表达式(Node a)Tree a -> Tree a -> Tree a 类型的函数。当你有

if (Node a) >= isHeap(left)

由于isHeap left 具有Bool 类型,编译器还期望>= 的左侧具有相同的类型。但是,您在编写该子句时遇到问题的原因是您没有子节点的值可以与父节点的值进行比较。

【讨论】:

    猜你喜欢
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    相关资源
    最近更新 更多