具有辅助功能的二叉搜索树谓词

时间:2019-10-10 07:04:42

标签: haskell tree binary-tree binary-search-tree predicate

data BinaryTree a = Null | Node (BinaryTree a) a (BinaryTree a)
deriving Show

type BSTree a = BinaryTree a

treeBSMax :: (Ord a) => BSTree a -> a
treeBSMax   btree = case btree of
        Null -> error
        Node _ val Null -> val
        Node _ val right -> treeBSMax right

treeBSMin :: (Ord a) => BSTree a -> a
treeBSMin btree = case btree of
       Null -> error
       Node Null val _ -> val
       Node left val _ -> treeBSMax left

isBSTree :: (Ord a) => BinaryTree a -> Bool
isBSTree btree = case btree of
      Null -> False
      Node Null val Null -> True
      Node lt val rt -> val >  treeBSMin lt && val < treeBSMax rt

如何使用treeBSMintreeBSMax作为isBSTree的辅助函数来查找树是否为二叉搜索树?

1 个答案:

答案 0 :(得分:1)

要将它们用作辅助函数,您需要首先使用Maybe从代码中删除 partiality

treeBSMax :: (Ord a) => BSTree a -> Maybe a
treeBSMax   btree = case btree of
        Null -> Nothing
        Node _ val Null -> Just val
        Node _ val right -> treeBSMax right

treeBSMin :: (Ord a) => BSTree a -> Maybe a
treeBSMin btree = case btree of
       Null -> Nothing
       Node Null val _ -> Just val
       Node left val _ -> treeBSMin left

isBSTree :: (Ord a) => BinaryTree a -> Bool
isBSTree btree = case btree of
      Null -> True                       -- changed it!
      Node Null val Null -> True
      Node lt val rt -> isBSTree lt       -- these two lines
                        && isBSTree rt     -- were missing !!
                        && inOrder (treeBSMax lt) val (treeBSMin rt)
                 where
                 inOrder Nothing  _ Nothing   =  True
                 inOrder Nothing  v (Just y)  =  v <= y
                 inOrder (Just x) v Nothing   =  x <= v
                 inOrder (Just x) v (Just y)  =  x <= v && v <= y

这当然不是很有效。 (为什么要留下 做练习)