Skip to content

Instantly share code, notes, and snippets.

@n2westman
Last active August 29, 2015 14:12
Show Gist options
  • Save n2westman/371494b4da13b30b4ffa to your computer and use it in GitHub Desktop.
Save n2westman/371494b4da13b30b4ffa to your computer and use it in GitHub Desktop.
Tail Recursive Binary Tree Check
#include <climits>
#include <queue>
typedef struct Holder {
Node* node;
int min;
int max;
Holder(Node* n, int min, int max): node(n), min(min), max(max) {}
} *Holder_p;
// Cracking the Coding Interview, Question 4.5
// Implement a function to check if a binary tree is a binary search tree
// See https://gist.github.com/lowellbander/d8c2bfcaebd8cbcdf755
// Tail Recursive (less elegant) implementation
bool isSearch(Node* root, int max = INT_MAX, int min = INT_MIN) {
queue<Holder_p> q;
q.push(new Holder(root, max, min));
return isSearchHelper(*q);
}
bool isSearchHelper(*queue<Holder_p> q) {
if(q->empty()) return true;
Holder_p hold = q->pop();
if (!hold->node) return isSearchHelper(q);
if (hold->node->value <= hold->min || hold->node->value > hold->max) return false;
q->push(new Holder(hold->node->left, hold->min, hold->node->value));
q->push(new Holder(hold->node->right, hold->node->value, hold->max));
delete hold;
return isSearchHelper(q);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment