在haskell中删除二进制搜索树中的函数

时间:2012-02-22 11:05:12

标签: haskell

如何实现删除二叉搜索树中元素的功能? 这是我的树:

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

我知道如果我的树是叶子

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

如果左右不是空的,我必须从右边删除最小值(或从左边最大值),它就成了根。但是,我该如何实现呢?

1 个答案:

答案 0 :(得分:1)

你应该实现一个功能

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

从树中删除最小元素并返回修改后的树和最小元素。然后删除算法变为:找到包含要删除项目的节点并调用

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