algorithm - 将红黑树改成AVL树算法

标签 algorithm data-structures avl-tree red-black-tree

<分区>

我需要编写一个算法来接收红黑树并将其转换为 AVL 树。 不必是完美的代码,伪代码也可以。甚至帮助我入门的主要想法。 不知道如何开始,请帮助。 谢谢!

最佳答案

你有一棵红黑树:

data Color = Black | Red
data RB a = NodeRB !Color (RB a) a (RB a) | TipRB

instance Foldable RB where
  foldMap _ TipRB = mempty
  foldMap f (NodeRB _ l v r) =
    foldMap f l <> f v <> foldMap f r

这给了我们 lengthtoList

你想要一棵 AVL 树:

data AVL a = NodeAVL Int (AVL a) a (AVL a) | TipAVL

fromListAVL :: Int -> Int -> [a] -> (AVL a, [a])
fromListAVL _ 0 xs = (TipAVL, xs)
fromListAVL _ _ [] = (TipAVL, [])
fromListAVL _ 1 (x:_) = NodeAVL 1 TipAVL x TipAVL
fromListAVL d xs = case fromListAVL (d-1) (n `quot` 2) xs of
  (NodeAVL _ l v r,[]) -> NodeAVL d l v r
  (t,(x:xs)) = NodeAVL d n t x $
                fst (fromListAVL (d-1) (n-n `quot` 2-1)) xs

rbToAVL :: RB a -> AVL a
rbToAVL rb = fromListAVL depth lrb (toList rb)
   where lrb = length rb
         depth = calculateDepth lrb -- write this!

关于algorithm - 将红黑树改成AVL树算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28793497/

相关文章:

c - 在 C 中实现最小堆

java - 现代文本编辑器中的片表和绳索的内存管理

algorithm - 从大集合构建 AVL 树的高效算法

algorithm - 给定顶点的度数,检查是否存在无向图

java - 将 pojo 类列表转换为 Jdom 树?

algorithm - 容量为 y、x*y 项目的 x 箱子,最大化总分,其中每个(项目,箱子)对都有一个相关联的分数

java - 单值映射 Java 的多个键

algorithm - Lukas-Kanade 步骤的高效 matlab 实现

c++ - 使用空树合并 AVL 树(C++ 模板)

c++ - 保存AVL树中节点下的叶子数