【问题标题】:Delete function in binary search tree in haskellHaskell中二叉搜索树中的删除函数
【发布时间】:2012-02-22 23:05:16
【问题描述】:

如何实现一个函数来删除二叉搜索树中的元素? 这是我的树:

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

我知道万一我的树是叶子

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

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

【问题讨论】:

  • 那么请下次标记。这是常见的做法。
  • @MatveyB.Aksenov 哦,对不起。下次我会记得的

标签: haskell


【解决方案1】:

你应该实现一个函数

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

从树中删除最小元素并返回修改后的树和最小元素。那么删除算法就变成了:找到要删除的item所在的节点,调用

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

【讨论】:

  • 如果delMin 是顶级的,那么让delMin :: Tree a -> Maybe (Tree a, a) 处理Leaf 可能会很好。
  • @DanielFischer:delMin,至少在当前不应从 BST 模块导出。它可能隐藏在where 子句中。
  • 它可能被认为通常有用,所以如果它被暴露,我宁愿安全地处理Leaf。如果只是本地的,那当然是不必要的混乱。
猜你喜欢
  • 2013-06-04
  • 2012-03-26
  • 1970-01-01
  • 2011-11-28
  • 1970-01-01
  • 2017-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多