Last active
December 3, 2015 06:53
-
-
Save antonio081014/0fa000d86cb5612e1327 to your computer and use it in GitHub Desktop.
Simple Task with Binary Tree written in Objective-C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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