百科问答小站 logo
百科问答小站 font logo



红黑树的实现可以有多精简(各种语言随意)? 第1页

  

user avatar   luo-bi-cheng 网友的相关建议: 
      

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

。如果想要再在这个基础上增加删除操作的话,可以参阅

cs.kent.ac.uk/people/st

,大概80行左右。

欢迎关注:




  

相关话题

  0基础开始,Leetcode200道题要多久左右? 
  有哪些「上帝算法」? 
  ICLR 2019 有什么值得关注的亮点? 
  2021-05-28:跳跃游戏 II。给定一个非负整数数组,你最初位于数组的第一个位...如何解答呢? 
  如果某一天证实随机数根本就不存在,会对生活的各个领域产生什么样的影响? 
  给人指路,说左右和说东西南北在算法上哪个更优? 
  如何证明一个数 n 的因子之和是 O(n) 的? 
  负数与负数相乘为什么会得正? 
  如何看待 2020 届校招算法工程师岗位求职人数远大于招聘岗位的现象? 
  如何学习数据结构? 

前一个讨论
你写过哪些比较酷的十行以内的 Matlab 代码?
下一个讨论
高校规定学生不删游戏就没收电脑,你怎么看?





© 2025-03-28 - tinynew.org. All Rights Reserved.
© 2025-03-28 - tinynew.org. 保留所有权利