vis*_*vis 5 algorithm haskell red-black-tree
我一直在玩Haskell中的RB树实现但是很难改变它,所以数据只放在叶子中,就像在二叉叶树中一样:
/+\
/ \
/+\ \
/ \ c
a b
Run Code Online (Sandbox Code Playgroud)
除了节点的颜色之外,内部节点还将保存其他信息,例如树的大小(如在普通RB树中,但数据保存在叶子中).我也不需要对要插入的数据进行排序.我只使用RB来获取平衡树,因为我插入数据但我想保持插入数据的顺序.
原始代码是(来自冈崎书):
data Color = R | B
data Tree a = E | T Color (Tree a ) a (Tree a)
insert :: Ord a => a -> Tree a -> Tree a
insert x s = makeBlack (ins s)
where ins E = T R E x E
ins (T color a y b)
| x < y = balance color (ins a) y b
| x == y = T color a y b
| x > y = balance color a y (ins b)
makeBlack (T _ a y b) = T B a y b
Run Code Online (Sandbox Code Playgroud)
我将其更改为:(导致异常:函数ins中的非详尽模式)
data Color = R | B deriving Show
data Tree a = E | Leaf a | T Color Int (Tree a) (Tree a)
insert :: Ord a => a -> Set a -> Set a
insert x s = makeBlack (ins s)
where
ins E = T R 1 (Leaf x) E
ins (T _ 1 a E) = T R 2 (Leaf x) a
ins (T color y a b)
| 0 < y = balance color y (ins a) b
| 0 == y = T color y a b
| 0 > y = balance color y a (ins b)
makeBlack (T _ y a b) = T B y a b
Run Code Online (Sandbox Code Playgroud)
原始余额功能是:
balance B (T R (T R a x b) y c) z d = T R (T B a x b) y (T B c z d)
balance B (T R a x (T R b y c)) z d = T R (T B a x b) y (T B c z d)
balance B a x (T R (T R b y c) z d) = T R (T B a x b) y (T B c z d)
balance B a x (T R b y (T R c z d)) = T R (T B a x b) y (T B c z d)
balance color a x b = T color a x b
Run Code Online (Sandbox Code Playgroud)
我从上面的代码中可以看出,我改变了一点.
在此先感谢您的帮助:)
编辑:对于我正在寻找的那种表示,Chris Okasaki建议我使用二进制随机访问列表,如他的书中所述.另一种方法是简单地调整Data.Set中的代码,Data.Set实现为权重平衡树.