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:

  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
时间: 2024-10-18 02:37:19

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

红黑树(Red Black Tree)

介绍另一种平衡二叉树:红黑树(Red Black Tree),红黑树由Rudolf Bayer于1972年发明,当时被称为平衡二叉B树(symmetric binary B-trees),1978年被Leonidas J. Guibas 和 Robert Sedgewick改成一个比较摩登的名字:红黑树. 红黑树和之前所讲的AVL树类似,都是在进行插入和删除操作时通过特定操作保持二叉查找树的平衡,从而获得较高的查找性能.自从红黑树出来后,AVL树就被放到了博物馆里,据说是红黑树有更好的效率,更高

数据结构 - 红黑树(Red Black Tree)插入详解与实现(Java)

最终还是决定把红黑树的篇章一分为二,插入操作一篇,删除操作一篇,因为合在一起写篇幅实在太长了,写起来都觉得累,何况是阅读并理解的读者. 红黑树删除操作请参考 数据结构 - 红黑树(Red Black Tree)删除详解与实现(Java) 现在网络上最不缺的就是对某个知识点的讲解博文,各种花样标题百出,更有类似"一文讲懂xxx","史上最简单的xxx讲解","xxx看了还不懂你打我"之类云云.其中也不乏有些理论甚至是举例都雷同的两篇不同文章,至于作

CF1208H Red Blue Tree

CF1208H Red Blue Tree 原本应该放在这里但是这题过于毒瘤..单独开了篇blog 首先考虑如果 $ k $ 无限小,那么显然整个树都是蓝色的.随着 $ k $ 逐渐增大,每个点都会有且仅有一次变色,我们考虑维护这个变色的时间 $ t $ .如果每个点的变色时间都已经被算出来,那么我们可以轻易解决题目的查询操作和修改 $ k $ , 也就是说修改 $ k $ 本身就是个假操作..只需要考虑的是修改单点颜色. 修改单点颜色,看起来就很 $ ddp $ .树链剖分后,用$ f(x)

1208 H. Red Blud Tree

1208 H. Red Blud Tree 题意: 给定一棵树和常数\(k\),每个结点的颜色为蓝色或红色,叶子结点颜色是给定的,内部结点的颜色为蓝色当且仅当蓝色儿子数\(-\)红色儿子数\(\geq k\).要求支持三种查询: 1.输出某个结点的颜色. 2.修改某个叶子结点的颜色 3.修改\(k\)的值. 题解: 先考虑没有操作2的情况.那么相当于查询某个结点在\(k\)为某个值的时候的颜色.当\(k=-\infty\)时,所有内部结点都为蓝色.对每个内部结点,当\(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 queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. Notes: You

(easy)LeetCode 225.Implement Stack using Queues

Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. empty() -- Return whether the stack is empty. Notes: You must use only s

【easy】225. Implement Stack using Queues

用队列实现栈.这个实现方法十分的简单,就是在push这一步的时候直接变成逆序. class MyStack { private: queue<int> q; queue<int> q2; public: /** Initialize your data structure here. */ MyStack() { } /** Push element x onto stack. */ void push(int x) { q.push(x); for(int i=0;i<q.

RBTree(RED,BLACK)Tree

红黑树是一棵二叉搜索树,它在每个节点上增加了一个存储位来表示节点的颜色,可以是Red或Black.通过对任何一条从根到叶子简单路径上的颜色来约束,红黑树保证最长路径不超过最短路径的两倍,因而近似于平衡. 红黑树是满足下面红黑性质的二叉搜索树 每个节点,不是红色就是黑色的 根节点是黑色的 如果一个节点是红色的,则它的两个子节点是黑色的(没有连续的红节点) 对每个节点,从该节点到其所有后代叶节点的简单路径上,均包含相同数目的黑色节点.(每条路径的黑色节点的数量相等) 每个叶子节点都是黑色的(这里的叶

ZOJ red black tree

#include <cstdio> #include <cstring> #include <cmath> #include <queue> #include <map> #include <vector> #include <iostream> #include <algorithm> using namespace std; typedef long long ll; const int maxn = 10