How do you delete the minimum in BST? I can’t seem to find a way to keep the tree
data BST = EmptyT
| Node Float BST BST
deriving (Eq, Show, Read)
deleteMin :: BST -> Maybe BST
deleteMin EmptyT = Nothing
deleteMin (Node x left right)
|left == EmptyT = ?
|otherwise = ?
do i need getters and setters?
Haskell does not have “getters and setter” in the OOP sense, though you can
come up with similar concepts. If you wish to delete a value in your binary
tree, you have to construct a new tree with the value missing. That is how you
“keep the tree.”
Assuming you are using a standard BST, then the leftmost node in the tree will
contain the minimum element. So, by traversing your tree towards the left,
you should eventually run into a situation that looks like
Node x EmptyT r.Any other node, you just recursively call
deleteMinon the left branch.This gives a function that looks like
You have to check the result of each call to
deleteMinto check forNothing. I don’t think you really need to return aMaybe BST, unless youreally need to indicate that there is no element to delete. It makes more
sense (to me at least) to just return an empty tree if there is nothing to
delete.
I think most would also consider the use of pattern matching preferable over using guards with an equality check.