Skip to content

Instantly share code, notes, and snippets.

@antonio081014
Last active December 3, 2015 06:53
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 antonio081014/0fa000d86cb5612e1327 to your computer and use it in GitHub Desktop.
Save antonio081014/0fa000d86cb5612e1327 to your computer and use it in GitHub Desktop.
Simple Task with Binary Tree written in Objective-C.
/**
* TreeNode:
* -val: NSNumber
* -left: TreeNode
* -right: TreeNode
*/
// Task: Build a Balanced Binary Search Tree from an Ordered Array.
- (TreeNode *)buildMinBSTFromArray:(NSArray *)array;
// Task: Level Traverse Binary Tree.
- (void)printBinaryTreeAtNode:(TreeNode *)root;
// Task: Check if a Binary Search Tree is valid.
- (BOOL)checkBST:(TreeNode *)root;
- (TreeNode *)buildMinBSTFromArray:(NSArray *)array
{
return [self buildMinBSTForArray:array from:0 to:array.count-1];
}
- (TreeNode *)buildMinBSTForArray:(NSArray *)array from:(NSInteger)left to:(NSInteger)right
{
if (left > right) return nil;
if (left == right) return [[TreeNode alloc] initWithValue:array[left]];
NSInteger mid = (left + right) / 2;
TreeNode *node = [[TreeNode alloc] initWithValue:array[mid]];
node.left = [self buildMinBSTForArray:array from:left to:mid-1];
node.right = [self buildMinBSTForArray:array from:mid+1 to:right];
return node;
}
// Using NSMutableArray as a Queue to maintain the order of TreeNodes.
- (void)printBinaryTreeAtNode:(TreeNode *)root
{
NSMutableArray *q = [NSMutableArray array];
[q addObject:root];
NSInteger cur = 1;
NSInteger nxt = 0;
while(q.count > 0) {
TreeNode *node = q[0];
[q removeObjectAtIndex:0];
printf("%d ", [node.val intValue]);
cur--;
if (node.left != nil) {
[q addObject:node.left];
nxt++;
}
if (node.right != nil) {
[q addObject:node.right];
nxt++;
}
// All current level's nodes have been visited
if(cur == 0) {
cur = nxt;
nxt = 0;
printf("\n");
}
}
}
- (BOOL)checkBST:(TreeNode *)root
{
return [self checkBST:root withMax:NSIntegerMax andMin:NSIntegerMin];
}
- (BOOL)checkBST:(TreeNode *)root withMax:(NSInteger)max andMin:(NSInteger)min
{
if(root == nil) return YES;
NSInteger val = [root.val integerValue];
if (val <= min || val >= max) return NO;
if (![self checkBST:root.left withMax:val andMin:min]) return NO;
if (![self checkBST:root.right withMax:max andMin:val]) return NO;
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment