I haven't implemented binary for a long time, and recently got a requirement to do that (to demonstrate some code), and I started using:
@interface NSNode : NSObject
@property (strong, nonatomic) NSNode *leftChild;
@property (strong, nonatomic) NSNode *rightChild;
but later on, it seems that whenever I need to do something to both nodes, I need to write it twice -- once for the left child and once for the right child, unless if I make what needs to be done into an extra method, and pass the proper arguments carefully -- there will be a lot of extra methods just to accomplish this.
If it had been done by using an NSMutableArray
typedef enum {
NSNodeLeft = 0,
NSNodeRight
} NSNodeLeftOrRightSide;
@interface NSNode : NSObject
@property (strong, nonatomic) NSMutableArray *children;
then I can always just use a loop to do something to both nodes:
for (NSNode *node in self.children) {
// do something
}
Or if an index is needed to tell whether it is left or right child:
[self.children enumerateObjectsUsingBlock:
^(NSNode *node, NSUInteger nodeIndex, BOOL *stop) {
// do something
}
];
and the nodeIndex
can be used to determined whether it is left or right child.
And what's more, this class can be easily extend to a tree with N-children. Is this actually a better practice? Is there any disadvantage except for a very small performance for using array? (I chose NSMutableArray
instead of NSArray
because if we ever need to make this N-children, we don't need to change it to NSMutableArray
all over the place).