Marco Sero
Marco Sero

Reputation: 460

Delete function in binary search tree in haskell

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??

Upvotes: 0

Views: 2696

Answers (1)

Fred Foo
Fred Foo

Reputation: 363487

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'

Upvotes: 1

Related Questions