Skip to content

Instantly share code, notes, and snippets.

@Goom11
Forked from lowellbander/isSearch.cpp
Last active August 29, 2015 14:12
Show Gist options
  • Save Goom11/f3216bd0aa1103ad9e0d to your computer and use it in GitHub Desktop.
Save Goom11/f3216bd0aa1103ad9e0d to your computer and use it in GitHub Desktop.
Converted the lowellbander/isSearch.cpp into a one liner solution
#include <climits>
// Cracking the Coding Interview, Question 4.5
// Implement a function to check if a binary tree is a binary search tree
// One-liner version
bool isSearch(Node* root, int max = INT_MAX, int min = INT_MIN) {
return (!root)
|| (
!(root->value <= min)
&& !(root->value > max)
&& isSearch(root->left, root->value, min)
&& isSearch(root->right, max, root->value)
);
}
// Alternative Tail-Recursive Solution:
// NOT DONE
bool isSearch1_rec(Node* root, int max, int min, bool acc) {
if (!root) {
return acc;
}
return (
!(root->value <= min)
&& !(root->value > max)
&& isSearch(root->left, root->value, min, acc)
&& isSearch(root->right, max, root->value, acc)
);
}
bool isSearch1(Node* root, int max = INT_MAX, int min = INT_MIN) {
return isSearch1_rec(root, max, min, True);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment