我可以重新present红黑树作为二进制叶树?红黑、present、制叶树

2023-09-11 00:09:25 作者:珍重

我一直在玩弄RB树实现在Haskell,但有困难改变了一点,因此数据只能放在叶子,就像一个二进制叶树:

I've been playing around with RB tree implementation in Haskell but having difficulty changing it a bit so the data is only placed in the leaves, like in a binary leaf tree:

    /+\
   /   \
 /+\    \
/   \    c
a   b

内部节点将持有的其他信息,例如树的大小,除节点的颜色(如在一个正常的RB树,但数据被保持在叶片ONY)。我也没有必要进行排序所插入的数据。我用包只得到一个平衡树,因为我插入数据,但我想保留其中数据插入的顺序。

The internal nodes would hold other information e.g. size of tree, in addition to the color of the node (like in a normal RB tree but the data is held in the leaves ony). I am also not needed to sort the data being inserted. I use RB only to get a balanced tree as i insert data but I want to keep the order in which data is inserted.

原来的code是(从Okasaki书):

The original code was (from Okasaki book):

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

我把它改为:(导致例外:功能插件非详尽模式)

I changed it to: (causing Exception:Non-exhaustive patterns in function 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

原有的平衡作用是:

The original balance function is:

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

我改了一下这从我的code以上显而易见的。

which i changed a bit as is obvious from my code above.

在此先感谢帮助:)

编辑:对于那种重presentation我在寻找,克里斯Okasaki曾建议我用的是二进制的随机访问列表,因为在他的著作中描述。另一种方法是简单地适应了code在在data.set,这是作为权重平衡树。

for the kind of representation I'm looking, Chris Okasaki has suggested I use the binary random access list, as described in his book. An alternative would be to simply adapt the code in Data.Set, which is implemented as weight balanced trees.

推荐答案

假设你的意思是插入::一 - &GT;树 - &GT;树一个,那么你的错误可能是由无子句插件(叶一)

Assuming you meant insert :: a -> Tree a -> Tree a, then your error probably stems from having no clause for ins (Leaf a).