The easy way to implement a Red-Black tree
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:
- No red node has a red child.
- Every path from the root to an empty node contains the same number of black nodes.
- 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的更多相关文章
- 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 ...
- [转载] 红黑树(Red Black Tree)- 对于 JDK TreeMap的实现
转载自http://blog.csdn.net/yangjun2/article/details/6542321 介绍另一种平衡二叉树:红黑树(Red Black Tree),红黑树由Rudolf B ...
- Red Black Tree 红黑树 AVL trees 2-3 trees 2-3-4 trees B-trees Red-black trees Balanced search tree 平衡搜索树
小结: 1.红黑树:典型的用途是实现关联数组 2.旋转 当我们在对红黑树进行插入和删除等操作时,对树做了修改,那么可能会违背红黑树的性质.为了保持红黑树的性质,我们可以通过对树进行旋转,即修改树中某些 ...
- CF1208H Red Blue Tree
CF1208H Red Blue Tree 原本应该放在这里但是这题过于毒瘤..单独开了篇blog 首先考虑如果 $ k $ 无限小,那么显然整个树都是蓝色的.随着 $ k $ 逐渐增大,每个点都会有 ...
- (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 ...
- (easy)LeetCode 225.Implement Stack using Queues
Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...
- 【easy】225. Implement Stack using Queues
用队列实现栈.这个实现方法十分的简单,就是在push这一步的时候直接变成逆序. class MyStack { private: queue<int> q; queue<int> ...
- 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 ...
- ZOJ - 4048 Red Black Tree (LCA+贪心) The 2018 ACM-ICPC Asia Qingdao Regional Contest, Online
题意:一棵树上有m个红色结点,树的边有权值.q次查询,每次给出k个点,每次查询有且只有一次机会将n个点中任意一个点染红,令k个点中距离红色祖先距离最大的那个点的距离最小化.q次查询相互独立. 分析:数 ...
随机推荐
- JavaScript浮动广告代码,容纯DIV/CSS对联漂浮广告代码,兼容性非常好的js右下角与漂浮广告代码
基于JavaScript代码实现随机漂浮图片广告,javascript图片广告 在网上有很多这样的代码,不过未必符合W3C标准,因为在头部加上<!DOCTYPE html>类似标签之后,漂 ...
- Hive的三种安装方式(内嵌模式,本地模式远程模式)
一.安装模式介绍: Hive官网上介绍了Hive的3种安装方式,分别对应不同的应用场景. 1.内嵌模式(元数据保村在内嵌的derby种,允许一个会话链接,尝试多个会话链接时会报错) ...
- SSH ProxyCommand
简单的说就是SSH层面的代理服务器,实现通过跳板机执行SSH相关命令到目标机器的代理服务.
- 高性能的JavaScript--加载和执行
写在前面 JavaScript在浏览器中的性能,可认为是开发者所要面对的最重要的可用性的问题,此问题因JavaScript的阻塞特征而复杂,也就是说JavaScript运行时其他的事情不能被浏览器处理 ...
- NXP恩智浦P87C51/52/54/58/591芯片解密单片机破解多少钱?
NXP恩智浦P87C51/52/54/58/591芯片解密单片机破解 芯片解密型号: P87C51x2.P87C52x2.P87C54x2.P87C58x2.P87C591 单片机解密 #####[ ...
- Git命令参考手册(文本版)
git init # 初始化本地git仓库(创建新仓库) git config --global user.name "xxx" # 配置用户名 git config --glob ...
- backup
1.垂直居中 2.敏捷开发,bug级别划分 3.bash构建,设计模式 4.git reset revoke rebase 区别 vue -validator 规则 • required: 是否是必 ...
- 使用Android Butterknife
我之前浏览过android butterknife 的使用 在android studio 中,很惊喜,已经成为一个插件来使用 这个android butterknife 最大的用处,就是直接生成la ...
- [svg 翻译教程]Polyline(折线)polygon(多边形)
原文: http://tutorials.jenkov.com/svg/polygon-element.html Polyline 虽然说这个 元素我没用过,但是还是蛮强大的,也翻译下 示例 < ...
- ANGULAR $HTTP请求【转】
angular使用post.get向后台传参的问题 一.问题的来源 我们都知道向后台传参可以使用get.put,其形式就类似于name=jyy&id=001.但是在ng中我却发现使用$http ...