4 * Simple implementation of a left-leaning red-black tree with 64-bit
5 * integer keys. The search operation will return the highest node <=
6 * the key; only search and insert are supported, but additional
7 * standard llrbtree operations can be coded up at will.
9 * See http://www.cs.princeton.edu/~rs/talks/LLRB/RedBlack.pdf for
10 * information about left-leaning red-black trees.
15 struct rbtree
*rb_search(struct rbtree
*tree
, uint64_t key
)
17 struct rbtree
*best
= NULL
;
22 else if (tree
->key
> key
)
32 static bool is_red(struct rbtree
*h
)
37 static struct rbtree
*rotate_left(struct rbtree
*h
)
39 struct rbtree
*x
= h
->right
;
42 x
->red
= x
->left
->red
;
47 static struct rbtree
*rotate_right(struct rbtree
*h
)
49 struct rbtree
*x
= h
->left
;
52 x
->red
= x
->right
->red
;
57 static void color_flip(struct rbtree
*h
)
60 h
->left
->red
= !h
->left
->red
;
61 h
->right
->red
= !h
->right
->red
;
64 struct rbtree
*rb_insert(struct rbtree
*tree
, struct rbtree
*node
)
71 if (is_red(tree
->left
) && is_red(tree
->right
))
74 if (node
->key
< tree
->key
)
75 tree
->left
= rb_insert(tree
->left
, node
);
77 tree
->right
= rb_insert(tree
->right
, node
);
79 if (is_red(tree
->right
))
80 tree
= rotate_left(tree
);
82 if (is_red(tree
->left
) && is_red(tree
->left
->left
))
83 tree
= rotate_right(tree
);