How do you implement trees in ANSI C (*)?
struct Element
{
...
struct Element *pChildElements; // Use dynamic array?
};
(*) I mean the most general definition of a tree (not binary trees).
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The best implementation approach (and there are many) might depend on the specific application. For example, storing child nodes or child pointers in an array might be preferable in some applications, and is completely unnecessary in other applications. Do you actually need index-based random access to the children? If so, use an array.
A classic non-array approach to implementing an arbitrary tree is to store two pointers in each node: a pointer to the fist child and a pointer to the next sibling.
I.e. each node essentially contains a pointer to the list of its children.
For example, a node with 3 children is represented by the following linked structure
This implementation can store any tree by using only two pointers in each node. No extra arrays necessary. Since child nodes are stored in a list, they are only accessible in sequential fashion.
The interesting observation that follows from this approach is that the resulting data structure can be thought of as a binary tree, i.e. an arbitrary tree can be represented by an equivalent binary tree.