Skip to content

Instantly share code, notes, and snippets.

@rgerard
Last active December 17, 2015 04:49
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 rgerard/5552943 to your computer and use it in GitHub Desktop.
Save rgerard/5552943 to your computer and use it in GitHub Desktop.
Determines whether a node is part of a valid binary search tree
// isValidBST() should return whether or not a given node is a valid binary search tree
//
// Assumes the following object:
// @interface Node
// @property (nonatomic) Node *left;
// @property (nonatomic) Node *right;
// @property (nonatomic) NSNumber *value;
// @end
- (BOOL)isValidBST(Node *root) {
NSMutableArray *inOrderArrayValues = [NSMutableArray array];
BOOL isValid = YES;
if(_checkValidBST(inOrderArrayValues, root)) {
// Check the final array values
// If the array is empty, there were no nodes, so return NO.
// Otherwise, iterate over the array and verify that the values are monotonically increasing
if([inOrderArrayValues count] == 0) {
isValid = NO;
} else {
NSInteger lastVal = [inOrderArrayValues objectAtIndex:0];
for(NSNumber *num in inOrderArrayValues) {
if([num integerValue] >= lastVal) {
lastVal = [num integerValue]
} else {
isValid = NO;
break;
}
}
}
} else {
isValid = NO;
}
return isValid;
}
- (BOOL)_checkValidBST(NSMutableArray *arrValues, Node *root) {
if(root == null) {
return YES;
} else {
// First check the left subtree. If valid, verify that the previous element is less than or equal to the current value.
BOOL checkSubtree = _checkValidBST(arrValues, root.left);
if(checkSubtree) {
// Check the previous node in the arrValues array, if not empty
// If the previous node's value is greater than our current value, this is not a valid BST
if(_isLastValueLessThanNode(arrValues, root)) {
[arrValues addObject:root.value];
return _checkValidBST(arrValues, root.right);
} else {
return NO;
}
} else {
return checkSubtree;
}
}
}
- (BOOL)_isLastValueLessThanNode(NSMutableArray *arrValues, Node *root) {
NSInteger totalElements = [arrValues count];
if(totalElements > 0 && [[arrValues objectAtIndex:(totalElements-1)] integerValue] > [root.value integerValue]) {
return NO;
} else {
return YES;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment