Jump to content
  • Advertisement
Sign in to follow this  
tordyvel

Tree node and leaf

This topic is 4407 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi there! I want to make a tree structure where only the leaf has data but can't figure out a cool way to do it. The tutorials I've found use some kind of node ID like: class CTree { public: struct _Node { bool isLeaf; Data *data; _Node *children; } Node; private: Node *root; // and so on }; But mixing the leaf data and children nodes is a bit ugly. Is there no cleaner way?

Share this post


Link to post
Share on other sites
Advertisement
For as many examples as Ive seen thats how its commonly done.

Might I add that you not forget to add a constructor for the node that initializes those pointers to 0/null. You can use this distinction later on by testing the data pointer to see if you have an internal node or a leaf node (since internal nodes will have null data pointers and leaf nodes will point to actual data).

Share this post


Link to post
Share on other sites
Quote:
Original post by tordyvel
But mixing the leaf data and children nodes is a bit ugly. Is there no cleaner way?


Yes there are 2 "cleaner way"s:

1. Use the composite design pattern.

2. Use tagged unions to emulate variants/algebraic data types, i suggest you do not attempt to write your own use a library in particular boost::variant. Look at the section on recursive variant types.

Each have their tradeoffs you need to think about but by default variants should be the first choice.

[Edited by - snk_kid on July 29, 2006 11:16:29 AM]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!