Created
May 5, 2024 14:53
-
-
Save brunoczim/a8e7cc6d81f65b62d44656126226eee5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Data.Tree where | |
data BinTree a | |
= Leaf | |
| Branch | |
{ binTreeLeft :: BinTree a | |
, binTreeNode :: a | |
, binTreeRight :: BinTree a | |
} | |
deriving (Show, Read, Eq, Ord) | |
data BstRange a | |
= BstRange | |
{ bstMin :: a | |
, bstMax :: a | |
} | |
deriving (Show, Eq) | |
data NotBst = NotBst deriving (Show, Eq) | |
ensureBst :: Ord a => BinTree a -> Either NotBst (Maybe (BstRange a)) | |
ensureBst Leaf = Right Nothing | |
ensureBst (Branch l x r) = case (minResult, maxResult) of | |
(Right minX, Right maxX) -> Right (Just (BstRange minX maxX)) | |
_ -> Left NotBst | |
where | |
minResult = case ensureBst l of | |
Right (Just rangeL) | |
| bstMax rangeL < x -> Right (bstMin rangeL) | |
| otherwise -> Left NotBst | |
Right Nothing -> Right x | |
Left err -> Left err | |
maxResult = case ensureBst r of | |
Right (Just rangeR) | |
| bstMin rangeR > x -> Right (bstMax rangeR) | |
| otherwise -> Left NotBst | |
Right Nothing -> Right x | |
Left err -> Left err |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment