I am in the process of refactoring this simple binary search tree code responsible for adding new values:
void add_internal(Node *root, int value) {
// Decide whether to insert left or right
if (root->value >= value) {
// Decide whether to insert here or down the subtree
if (root->left) {
add_internal(root->left, value);
} else {
root->left = create_node(value);
}
} else {
// Decide whether to insert here or down the subtree
if (root->right) {
add_internal(root->right, value);
} else {
root->right = create_node(value);
}
}
}
to this:
Node **relevant_node = (root->value >= value) ? &root->left : &root->right;
if (*relevant_node) {
add_internal(*relevant_node, value);
} else {
*relevant_node = create_node(value);
}
Both solutions work. My refactored one tho is pretty much the result of trial and error, will it be as robust as the first solution?