Skip to content

Instantly share code, notes, and snippets.

@jaybaird
Last active December 19, 2015 19:09
Show Gist options
  • Save jaybaird/6003951 to your computer and use it in GitHub Desktop.
Save jaybaird/6003951 to your computer and use it in GitHub Desktop.
Binary Tree with NSArray
#import <Foundation/Foundation.h>
@interface Node : NSObject
@property (nonatomic) NSInteger identifier;
@property (nonatomic, copy) NSString *value;
+ (Node *)nodeWithIdentifier:(NSInteger)identifier value:(NSString *)value;
@end
@implementation Node
+ (Node *)nodeWithIdentifier:(NSInteger)identifier value:(NSString *)value {
Node *node = [[self alloc] init];
node.identifier = identifier;
node.value = value;
return node;
}
- (NSString *)description {
return [NSString stringWithFormat:@"%ld: %@", _identifier, _value];
}
@end
@interface BinaryTree : NSObject
@property (nonatomic, retain) NSMutableArray *tree;
@property (nonatomic, copy) NSComparator comparator;
- (instancetype)initWithComparator:(NSComparator)comparator;
- (NSInteger)insert:(Node *)node;
- (NSInteger)search:(Node *)node;
@end
@implementation BinaryTree
- (instancetype)initWithComparator:(NSComparator)comparator {
self = [super init];
if (self) {
_comparator = comparator;
_tree = [NSMutableArray array];
}
return self;
}
- (void)insert:(Node *)node {
[_tree insertObject:node atIndex:[self search:node]];
}
- (NSInteger)search:(Node *)node {
return [_tree indexOfObject:node
inSortedRange:NSMakeRange(0, _tree.count)
options:NSBinarySearchingInsertionIndex
usingComparator:_comparator];
}
- (NSString *)description {
return [_tree description];
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
BinaryTree *btree = [[BinaryTree alloc] initWithComparator:^(Node *n1, Node *n2) {
if (n1.identifier > n2.identifier) {
return (NSComparisonResult)NSOrderedDescending;
}
if (n1.identifier < n2.identifier) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
[btree insert:[Node nodeWithIdentifier:1 value:@"hoagies"]];
[btree insert:[Node nodeWithIdentifier:2 value:@"hoagies n grinders"]];
[btree insert:[Node nodeWithIdentifier:-1 value:@"subs"]];
NSLog(@"%@", btree);
NSLog(@"%ld", [btree search:[Node nodeWithIdentifier:-1 value:@"subs"]]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment