如何检查节点是否为二叉树中的叶子(Haskell)

我需要检查节点是否是我的二叉树中的叶子。这是我当前的代码。

isLeaf :: Eq a => a -> BTree a -> Bool
isLeaf node tree@(Node el left right) 
    | tree == Empty                                 = False
    | right == Empty && left == Empty && node == el = True
    | otherwise                                     = isLeaf node left && isLeaf node right

它向我发送一条错误消息,提示: “ hw3_71937.hs:C:\ Users \ lenovo \ Desktop \ ... \\ HASKELL \ hw3_71937.hs:(22,1)-(25,91):函数isLeaf中的非穷举模式”

我不知道如何递归检查下一个节点(如果它是叶子)。任何帮助将不胜感激。

评论
  • 续写呐份情
    续写呐份情 回复

    守卫:

      | tree == Empty = False

    永远不可能是真的,因为在您的条款的开头:

    isLeaf node tree@(Node el left right)

    you say that this is a Node, not an Empty. This is also the case that you did not cover: in case you pass an Empty (and eventually you can pass an Empty due to recursion), no pattern will match.

    话虽如此,我认为您使这一点变得太复杂了。您可以这样写:

    isLeaf :: Eq a => a -> BTree a -> Bool
    isLeaf _ Empty = False
    isLeaf x (Node x' Empty Empty) = x == x'
    isLeaf x (Node _ l r) = isLeaf x l || isLeaf x r

    or with a where clause:

    isLeaf :: Eq a => a -> BTree a -> Bool
    isLeaf x = go
        where go Empty = False
              go (Node x' Empty Empty) = x == x'
              go (Node _ l r) = go l || go r