Skip to content

Instantly share code, notes, and snippets.

@pervognsen
Created March 25, 2020 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pervognsen/a00a631767de0b5fcf81fbf9bf9c9b0c to your computer and use it in GitHub Desktop.
Save pervognsen/a00a631767de0b5fcf81fbf9bf9c9b0c to your computer and use it in GitHub Desktop.
// Version 1: Recursion.
node_t *find1(node_t *node, int key) {
if (!node) {
return NULL;
}
if (key < node->key) {
return find1(node->left, key);
} else if (key == node->key) {
return node;
} else {
return find1(node->right, key);
}
}
// All the recursive calls are in tail position. This means that when the recursion unwinds the calling
// function just forwards the return value without doing additional work before passing it along.
// This means it is equivalent to iteration (without an auxiliary stack).
// Version 2: Wrap infinite loop around body and replace tail calls with in-place updates to arguments.
node_t *find2(node_t *node, int key) {
for (;;) {
if (!node) {
return NULL;
}
if (key < node->key) {
node = node->left;
key = key;
} else if (key == node->key) {
return node;
} else {
node = node->right;
key = key;
}
}
}
// Version 3: Replace infinite loop with while loop and remove useless assignments.
node_t *find3(node_t *node, int key) {
while (node) {
if (key < node->key) {
node = node->left;
} else if (key == node->key) {
return node;
} else {
node = node->right;
}
}
return NULL;
}
// Version 4: Replace multiple exits with one exit.
node_t *find4(node_t *node, int key) {
while (node && key != node->key) {
if (key < node->key) {
node = node->left;
} else {
node = node->right;
}
}
return node;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment