diff options
| author | mo khan <mo.khan@gmail.com> | 2020-08-29 18:38:41 -0600 |
|---|---|---|
| committer | mo khan <mo.khan@gmail.com> | 2020-08-29 18:38:41 -0600 |
| commit | 4a9fb5407ef1ae146a469adf4c1f2fa95f876926 (patch) | |
| tree | 5445a1552d83b78b89d79f9f7b51937ff0d1373a /src | |
| parent | c898a2bc603bff1cc21f23f0f2a2f79121b8af25 (diff) | |
refactor: collapse some conditional logic
Diffstat (limited to 'src')
| -rw-r--r-- | src/03/rb_tree.c | 41 |
1 files changed, 21 insertions, 20 deletions
diff --git a/src/03/rb_tree.c b/src/03/rb_tree.c index 3e3f234..617e6f9 100644 --- a/src/03/rb_tree.c +++ b/src/03/rb_tree.c @@ -108,29 +108,29 @@ void insert_repair_tree(RBTree *tree) { } } +static int compare(int a, int b) { + return a == b ? 0 : a < b ? -1 : 1; +} + static void insert(RBTree *root, RBTree *node) { - if (root) { - if (node ->value < root->value) { - if (root->left) { - insert(root->left, node); - return; - } else { - root->left = node; - } - } else { - if (root->right) { - insert(root->right, node); - return; - } else { - root->right = node; - } + if (!root) + return; + + if (compare(node->value, root->value) < 0) { + if (root->left) + insert(root->left, node); + else { + root->left = node; + node->parent = root; + } + } else { + if (root->right) + insert(root->right, node); + else { + root->right = node; + node->parent = root; } } - - node->parent = root; - node->left = NULL; - node->right = NULL; - node->colour = red; } static void print_tree(RBTree *tree, int level) { @@ -166,6 +166,7 @@ RBTree *rb_tree_insert(RBTree *tree, int value) { if (tree == NULL) return node; + node->colour = red; insert(tree, node); insert_repair_tree(node); |
