20行实现一个完整的红黑树的话,还是太困难了。如果不考虑删除操作的话,可以参考
Purely Functional Data Structures一书当中3.3节介绍的用Haskell实现的一个红黑树。
module RedBlackSet( empty , member , insert ) where data Tree a = Empty | T Color (Tree a) a (Tree a) data Color = R | B empty :: Ord a => Tree a empty = Empty member :: Ord a => Tree a -> a -> Bool member (T _ left e right) x | x == e = True | x < e = member left x | x > e = member right x member Empty _ = False insert :: Ord a => a -> Tree a -> Tree a insert x s = let T _ a y b = ins s in T B a y b where ins s'@(T color a' y' b') | x < y' = build color (ins a') y' b' | x > y' = build color a' y' (ins b') | otherwise = s' ins Empty = T R Empty x Empty build :: Color -> Tree a -> a -> Tree a -> Tree a build 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) build 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) build 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) build 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) build color left x right = T color left x right
看了下,大概30度行。上述实现直接搬运自
The easy way to implement a Red-Black tree。如果想要再在这个基础上增加删除操作的话,可以参阅
http://www. cs.kent.ac.uk/people/st aff/smk/redblack/Untyped.hs,大概80行左右。
欢迎关注: