parser.c: fix stylistic nitpick
[nasm/avx512.git] / rbtree.c
blob618b4f8dff4621ee4cd3de093c21a71a99927bfb
1 /*
2 * rbtree.c
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.
13 #include "rbtree.h"
15 struct rbtree *rb_search(struct rbtree *tree, uint64_t key)
17 struct rbtree *best = NULL;
19 while (tree) {
20 if (tree->key == key)
21 return tree;
22 else if (tree->key > key)
23 tree = tree->left;
24 else {
25 best = tree;
26 tree = tree->right;
29 return best;
32 static bool is_red(struct rbtree *h)
34 return h && h->red;
37 static struct rbtree *rotate_left(struct rbtree *h)
39 struct rbtree *x = h->right;
40 h->right = x->left;
41 x->left = h;
42 x->red = x->left->red;
43 x->left->red = true;
44 return x;
47 static struct rbtree *rotate_right(struct rbtree *h)
49 struct rbtree *x = h->left;
50 h->left = x->right;
51 x->right = h;
52 x->red = x->right->red;
53 x->right->red = true;
54 return x;
57 static void color_flip(struct rbtree *h)
59 h->red = !h->red;
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)
66 if (!tree) {
67 node->red = true;
68 return node;
71 if (is_red(tree->left) && is_red(tree->right))
72 color_flip(tree);
74 if (node->key < tree->key)
75 tree->left = rb_insert(tree->left, node);
76 else
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);
85 return tree;