Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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