Red-Black trees are notorious for being nightmares of pointer manipulation. Instructors will show the theory, but won’t torture their students to implement one. Interviewers will avoid asking about it. They probably couldn’t do it themselves.

You should be vaguely familiar with how you might balance a tree. The details, however, are probably unnecessary for the purposes of an interview. – Gayle McDowell, Cracking the coding interview

If you’re proficient in a functional language, you owe it to yourself to implement a Red-Black tree. You’ll be one of the few people that can code a Red-Black tree on a whiteboard.

It will make you realize why people are so excited about the whole functional programming thing.


What is a Red-Black Tree?

A Red-Black tree is a balanced binary search tree. Every node is colored red or black. Three rules hold:

  1. No red node has a red child.
  2. Every path from the root to an empty node contains the same number of black nodes.
  3. An empty node is always black.

Draw a tree with these rules. Notice it’s always relatively-balanced. Try to draw one as unbalanced as possible. You won’t get far.

You can prove the maximum depth of a node is at most 2


Implementation

Let’s implement a set with a Red-Black tree. At minimum we’ll need a member function and an insertfunction.


Data

A tree can be empty, or it can be a node with two subtrees, a color, and an element.

data Tree a = Empty -- Empty does not need a color, it's always black.
| T Color (Tree a) a (Tree a) data Color = R
| B

Member

The member function searches for an element. It’s a binary search.

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

The insert function uses the function build, which is a constructor that makes sure the node is balanced.

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

There are four cases when build needs to adjust a node. It detects the case when a black parent has a red child with a red child. It shifts the nodes around to fix it. The solution is the same in every case. (Notice the right hand sides of build are the same).

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

Afterwards

That’s it. You have a Red-Black tree.

If you want to learn more, read Purely Functional Data Structures by Chris Okasaki. I stole most of my implementation from this book. The build diagram is also from the book.




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

The easy way to implement a Red-Black tree的更多相关文章

  1. Red–black tree ---reference wiki

    source address:http://en.wikipedia.org/wiki/Red%E2%80%93black_tree A red–black tree is a type of sel ...

  2. [转载] 红黑树(Red Black Tree)- 对于 JDK TreeMap的实现

    转载自http://blog.csdn.net/yangjun2/article/details/6542321 介绍另一种平衡二叉树:红黑树(Red Black Tree),红黑树由Rudolf B ...

  3. Red Black Tree 红黑树 AVL trees 2-3 trees 2-3-4 trees B-trees Red-black trees Balanced search tree 平衡搜索树

    小结: 1.红黑树:典型的用途是实现关联数组 2.旋转 当我们在对红黑树进行插入和删除等操作时,对树做了修改,那么可能会违背红黑树的性质.为了保持红黑树的性质,我们可以通过对树进行旋转,即修改树中某些 ...

  4. CF1208H Red Blue Tree

    CF1208H Red Blue Tree 原本应该放在这里但是这题过于毒瘤..单独开了篇blog 首先考虑如果 $ k $ 无限小,那么显然整个树都是蓝色的.随着 $ k $ 逐渐增大,每个点都会有 ...

  5. (easy)LeetCode 232.Implement Queue using Stacks

    Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of ...

  6. (easy)LeetCode 225.Implement Stack using Queues

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  7. 【easy】225. Implement Stack using Queues

    用队列实现栈.这个实现方法十分的简单,就是在push这一步的时候直接变成逆序. class MyStack { private: queue<int> q; queue<int> ...

  8. 2018 ICPC青岛网络赛 B. Red Black Tree(倍增lca好题)

    BaoBao has just found a rooted tree with n vertices and (n-1) weighted edges in his backyard. Among ...

  9. ZOJ - 4048 Red Black Tree (LCA+贪心) The 2018 ACM-ICPC Asia Qingdao Regional Contest, Online

    题意:一棵树上有m个红色结点,树的边有权值.q次查询,每次给出k个点,每次查询有且只有一次机会将n个点中任意一个点染红,令k个点中距离红色祖先距离最大的那个点的距离最小化.q次查询相互独立. 分析:数 ...

随机推荐

  1. PHP Math 函数

    abs() 绝对值. 3 acos() 反余弦. 3 acosh() 反双曲余弦. 4 asin() 反正弦. 3 asinh() 反双曲正弦. 4 atan() 反正切. 3 atan2() 两个参 ...

  2. linux学习日记之目录配制

    linux目录管理遵循FHS标准,主要目标是希望让使用者可以了解已安装软件通常放置于哪个目录上,所以他们希望独立的软件开发商.操作系统制作者.以及想要维护系统的用户,都遵循FHS的标准.也就是说FHS ...

  3. CentOS7 下ifconfig command not found解决办法

    今天尝鲜用VMWare安装了CentOS7,选择了最小安装包模式,安装完毕之后想查看一下本机的ip地址,发现报错 # ifcon -bash: ifconfig: command not found ...

  4. 鱼搜_鱼搜官网_鱼搜搜索_http://www.7yusou.com

    收集了N多视频小站,然后花了3天时间弄了一个鱼搜搜索网站.欢迎大家访问哟. http://www.7yusou.com

  5. AugularJS特性

    AugularJS特性 AngularJS是一个新出现的强大客户端技术,提供给大家的一种开发强大应用的方式.这种方式利用并且扩展HTML,CSS和javascript,并且弥补了它们的一些非常明显的不 ...

  6. Swift 之模糊效果(毛玻璃效果,虚化效果)的实现

    前言: 之前项目中有用到过Objective-C的的模糊效果,感觉很是不错,而且iOS8之后官方SDK也直接提供了可以实现毛玻璃效果的三个类:UIBlurEffect.UIVibrancyEffect ...

  7. 接口测试第三课(HTTP协议简介) -- 转载

    一.打开百度URL详解: 用浏览器打开百度网址,输入任意关键字搜索后: 详细URL地址复制出来如下 https://www.baidu.com/s?ie=utf-8&f=8&rsv_b ...

  8. servlet jsp jdbc bootstrarp mvc分层模式实现的第一个项目

    登录注册界面 这是一个注册和登录的界面 用到了前端页面中自带的一点H5的标签和属性---巩固下 邮箱格式 :type="email"  不能为空:  required=" ...

  9. 前端CSS规范整理_转载、、、

    一.文件规范 1.文件均归档至约定的目录中. 具体要求通过豆瓣的CSS规范进行讲解: 所有的CSS分为两大类:通用类和业务类.通用的CSS文件,放在如下目录中: 基本样式库 /css/core 通用U ...

  10. [资料分享]尚硅谷JavaWeb

    下载链接: 链接:https://pan.baidu.com/s/1pKMclsv 密码:8fbh