Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
964 views
in Technique[技术] by (71.8m points)

algorithm - Can I represent a Red-black tree as binary leaf tree?

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

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.

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

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

Thanks in advance for help :)

EDIT: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...