Logo

Programming-Idioms

  • Lisp
  • Obj-c

Idiom #17 Create a Tree data structure

The structure must be recursive. A node may have zero or more children. A node has access to its children nodes, but not to its parent.

@import Foundation;
@interface Node:NSObject
@property id value; // id means any object value
@property NSMutableArray *children;
@end

// usage like
Node *n=[Node new];
n.value=@1;
[n.children addObject:otherNode];
[n.children removeLastObject];

// somewhere needed also
@implementation Node
-(instancetype)init {
  if (!(self=[super init])) return nil;
  _children=[NSMutableArray array];
  return self;
}
@end

Compare also #9
typedef struct node_s
{
    int value;
    struct node_s *nextSibling;
    struct node_s *firstChild;
} node_t;

New implementation...