0

The title pretty much says it all. I'm just having a little computer science exercise and am building a Tree. I want a node to be able to add a sibling which requires one to first get a reference to the parent, obviously. I was wondering what is the "correct" way, by definition of what a Tree is, to do such a thing?

2 Answers 2

3

Well, you add a child to the parent.

But consider that the root can't add a sibling. This means that sibling-adding isn't something that a node in general knows how to do. You can check whether the parent is null, but (assuming you're doing OO) purists would say to put "add sibling" somewhere outside of your node class. Often you have a wrapping "Tree" class which holds a root node; the Tree class might be a good place for a static "add sibling" method.

0

A lot of trees I've worked with in the wild (window trees in display servers and so on) have just two pointers: first_child and next_peer. add_child is implemented in terms of if(first_child) first_child->add_peer(child) else first_child = child;. So in this implementation style there is a function explicitly for adding siblings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.