Created
December 18, 2016 11:54
-
-
Save wpsteak/705d21958db14bf96bda6820779e4f22 to your computer and use it in GitHub Desktop.
/traverse the PWNode in inorder
This file contains hidden or 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
#import <Foundation/Foundation.h> | |
@interface PWNode : NSObject <NSCopying> | |
typedef void (^PWNodeEnumerateBlock)(NSString *value); | |
@property (nonatomic, copy) NSString *value; | |
@property (nonatomic, strong) PWNode *leftNode; | |
@property (nonatomic, strong) PWNode *rightNode; | |
@property (nonatomic, copy) PWNodeEnumerateBlock nodeEnumerateblock; | |
@end | |
@implementation PWNode | |
- (id)copyWithZone:(NSZone *)zone | |
{ | |
PWNode *node = [[PWNode alloc] init]; | |
node.value = self.value; | |
node.leftNode = [self.leftNode copy]; | |
node.rightNode = [self.rightNode copy]; | |
return node; | |
} | |
+ (PWNode *)nodeWithValue:(NSString *)value | |
{ | |
PWNode *node = [[PWNode alloc] init]; | |
node.value = value; | |
return node; | |
} | |
//traverse the tree in inorder | |
- (void)inorder:(PWNode *)node | |
{ | |
if(node != nil) { | |
[self inorder:node.leftNode]; | |
self.nodeEnumerateblock(node.value); | |
[self inorder:node.rightNode]; | |
} | |
} | |
- (void)enumerateNodesUsingBlock:(PWNodeEnumerateBlock)block | |
{ | |
self.nodeEnumerateblock = block; | |
[self inorder:self]; | |
} | |
@end | |
int main (int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
PWNode *rootNode = [PWNode nodeWithValue:@"A"]; | |
rootNode.leftNode = [PWNode nodeWithValue:@"B"]; | |
rootNode.rightNode = [PWNode nodeWithValue:@"C"]; | |
rootNode.leftNode.leftNode = [PWNode nodeWithValue:@"D"]; | |
rootNode.leftNode.rightNode = [PWNode nodeWithValue:@"E"]; | |
rootNode.rightNode.leftNode = [PWNode nodeWithValue:@"F"]; | |
rootNode.rightNode.rightNode = [PWNode nodeWithValue:@"G"]; | |
[rootNode enumerateNodesUsingBlock:^(NSString *value) { | |
NSLog(@"%@", value); | |
}]; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment