I have a problem: build a tree relationship parent/child like this one:
Can you review this piece of code please since I am convinced it could be improved?
struct item {
char value;
std::list<item*> children;
};
I write a comparison function for a sort :
bool compareChild(const item *first, const item *second)
{
return ( first->value < second->value );
}
a function to get the parent:
item *getTopParent(const char src_data[][2], int len)
{
for (int i = 0; i < len; ++i)
{
if (src_data[i][0] == '\0')
{
item* head = new item;
head->value = src_data[i][1];
return head;
}
}
return NULL;
}
Two functions to push the children:
bool PushChildren(const char src_data[][2], int len, item *parent)
{
bool parentGotChildren = false;
for (int i = 0; i < len; ++i)
{
if (src_data[i][0] == parent->value)
{
item* child = new item;
child->value = src_data[i][1];
parent->children.push_back(child);
parentGotChildren = true;
}
}
parent->children.sort(compareChild);
return parentGotChildren;
}
bool PushChildrenforAParent(const char src_data[][2], item *parent, int len)
{
bool hasGotAChild = true;
std::list<item*>::iterator itchild = parent->children.begin();
std::list<item*>::iterator childLast = parent->children.end();
while (hasGotAChild && (itchild != childLast))
{
hasGotAChild = PushChildren( src_data, len, *itchild);
if (hasGotAChild)
{
hasGotAChild = PushChildrenforAParent( src_data, *itchild, len);
}
++itchild;
}
return hasGotAChild;
}
A function to initialise the "tree":
item* initialize_tree(const char src_data[][2], int len)
{
bool hasTopParentGotAChild = false;
//initialisation of the head
item *head = getTopParent( src_data, len);
if (head != NULL)
{
hasTopParentGotAChild = PushChildren( src_data, len, head);
if (head != NULL)
{
if (hasTopParentGotAChild)
{
PushChildrenforAParent(src_data, head, len);
}
return head;
}
else
{
return NULL;
}
}
return NULL;
}