0

How can I implement a function to delete an element in a binary search tree? This is my tree:

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

I know that in case my tree is a Leaf

delete :: (Ord a) => a -> Tree a -> Tree a
delete _ Leaf   = Leaf

and in case left and right are not empty, I have to delete the minimum from right (or maximum from left) and it became the root. But, how can I implement it??

2
  • Then please tag it so next time. It's common practice here. Commented Feb 22, 2012 at 15:47
  • @MatveyB.Aksenov oh, sorry. next time I'll remember Commented Feb 22, 2012 at 19:22

1 Answer 1

1

You should implement a function

delMin :: Tree a -> (Tree a, a)

that deletes the minimum element from a tree and returns both the modified tree and the minimum element. Then the deletion algorithm becomes: find the node with the item to be deleted and call

-- delete' n  deletes the node n and returns a modified BST
delete' :: Ord a => Tree a -> Tree a
delete' (Node _ l Leaf)  =  l
delete' (Node _ Leaf r)  =  r
delete' (Node _ l r)     =  let (r', min) = delMin r in
                              Node min l r'
Sign up to request clarification or add additional context in comments.

3 Comments

If delMin is top-level, it is probably good to make it delMin :: Tree a -> Maybe (Tree a, a) to deal with Leaf.
@DanielFischer: delMin, at least in current should not be exported from the BST module. It might be hidden in a where clause.
It might be considered generally useful, though, so if it is exposed, I'd rather safely deal with Leaf. If it's just a local, that would of course be unnecessary clutter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.