Pascal
Pascal

Reputation: 12885

should a tree have exactly one root node

I want to display a tree structure. Do i really need to give the user/tree a predefined hardcoded root node like "RootUnit" where he can add his children or descendants?

Does this make sense or cause only trouble when adding nodes?

Upvotes: 3

Views: 5264

Answers (5)

Servy
Servy

Reputation: 203820

It depends on the context. From a strict mathematical definition, you cannot have multiple root nodes to a tree. However, there some implementations of trees that ignore that and have multiple top level nodes anyway (Such as the TreeView control you tagged this question with). You simply need to ask yourself if your particular program would be better or worse with multiple top level nodes. Given that we know nothing else about your program it's not a decision we can really make for you.

Upvotes: 2

GETah
GETah

Reputation: 21449

A tree by definition has only one root and every child node has exactly one parent (except the root which has no parent). If these restrictions are not met then your tree is no longer a tree but a graph (oriented or not)

Upvotes: 2

BlackVegetable
BlackVegetable

Reputation: 13064

Rather than using the same constructor for every node, supply a default constructor used for the root node and one for everything else. It isn't ugly, and it works.

public Node()
{
  // Set properties if you'd like.
  // such as having no children yet or whatnot.
}

public Node(Node parent)
{
  // Similar to Node()
}

See! Nice and clean.

Upvotes: 1

LosManos
LosManos

Reputation: 7692

If you have two roots then you have two trees.

Upvotes: 5

Rango
Rango

Reputation: 1115

A tree should have only one root. But you need not hardcode a root. Just treat the first created tree node as root.

Upvotes: 2

Related Questions