By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,482 Members | 1,611 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,482 IT Pros & Developers. It's quick & easy.

How to deal with Tree with several branchs?

P: n/a
My program deal with a several level tree with several branchs. The
amount of branchs from father node is not known. So I want to creat a
tree with dynamic branchs.

Now I use the structure:
typedef struct gnodes
{
int level; //tree level
struct gnodes* pfather;
struct gnodes* pbrother;
struct gnodes* pchild;
struct gnodes* puncle;
} gnode;

The child pointer link one by one form a chain, something like:
Father(i)->Child(1)->Child(2)->...->Child(n-1)->Child(n).
But I can not search child randomly.

How to design a better structure?
Any suggestions will be appreciated!

Best regards,
Davy

Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Davy wrote:
My program deal with a several level tree with several branchs. The
amount of branchs from father node is not known. So I want to creat a
tree with dynamic branchs.

Now I use the structure:
typedef struct gnodes
{
int level; //tree level
struct gnodes* pfather;
struct gnodes* pbrother;
struct gnodes* pchild;
struct gnodes* puncle;
} gnode;

The child pointer link one by one form a chain, something like:
Father(i)->Child(1)->Child(2)->...->Child(n-1)->Child(n).
But I can not search child randomly.


You could just allocate an array and when you need to further
populate it you just reallocate, extend and copy the child elements.

Basically you need only one procedure:

Changed [gnodes * pchild] to [gnodes ** pchild] since it now
is a pointer to an array of pointers to gnodes, and
initialize both pchild and pCurrentChildSize to 0(null) and
it should work, even delete[] should be safe when the first element
is pushed.

void gnodes::push(gnodes * element)
{
gnodes ** temp = new gnodes*[pCurrentChildSize + 1];
for(unsigned i = 0; i < pCurrentChildSize; ++i)
{
temp[i] = pchild[i];
}
temp[pCurrentChildSize] = element;
++pCurrentChildSize;
delete[] pchild;
pchild = temp;
}

Tobias
--
IMPORTANT: The contents of this email and attachments are confidential
and may be subject to legal privilege and/or protected by copyright.
Copying or communicating any part of it to others is prohibited and may
be unlawful.
Jul 23 '05 #2

P: n/a
Davy wrote:
My program deal with a several level tree with several branchs. The
amount of branchs from father node is not known. So I want to creat a
tree with dynamic branchs.

The first thing you'd better do is pick a language. You posted the same
question to comp.lang.c.


Brian
Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.