Object
|
+---DTree
The tree class implements a n-tree collection. It stores objects in a tree of nodes. Because there is no key or index available to store and remove the objects, the objects can only be stored, inserted and removed by the tree iterator: class DTreeIterator.
#include <stdio.h>
#include "ofc/DTree.h"
#include "ofc/DText.h"
int main(int argc, char *argv[])
{
DTree *tree = [DTree new ];
DTreeIterator *iter = [DTreeIterator alloc];
DText *str1;
DText *str2;
int level;
[iter init :tree]; // Init the iterator with the tree
str1 = [DText new]; [str1 set :"root"];
[iter append :str1]; // Set the root
str1 = [DText new]; [str1 set :"child1"];
[iter append :str1]; // Append a child to the root and ..
[iter parent]; // .. move the iterator back to the root
str1 = [DText new]; [str1 set :"child2"]; // Append again a child to the root and ..
[iter append :str1]; // .. keep the iterator on the child
str1 = [DText new]; [str1 set :"child21"]; // Append a child for the chilld
[iter append :str1];
str1 = [DText new]; [str1 set :"child22"]; // Append another child
[iter after :str1];
[iter parent]; // Move iter back to level 2
str1 = [DText new]; [str1 set :"child4"];
[iter after :str1]; // Append after the child a new child
str2 = [DText new]; [str2 set :"child3"];
[iter before :str2]; // Prepend before the child a new child
printf("Elements in the tree:%ld.\n", [tree length]);
printf("Tree %s child3.\n", ([tree has :str2] ? "has" : "has not"));
level = 1;
str1 = [iter root]; // Move the iter to the root
while (str1 != nil)
{
printf("Level:%d Element:%s.\n", level, [str1 cstring]);
if ([iter hasChildren]) // If the node has children, than move to the first child
{
level++;
str1 = [iter child];
}
else if ([iter isLast]) // If all children done, than move to the next of the parent
{
level--;
str1 = [iter parent];
if (str1 != nil)
str1 = [iter next];
}
else
{
str1 = [iter next]; // Else next child
}
}
[iter free]; // Cleanup
[tree free];
return 0;
}