10.7. Creating an n-ary Tree
Problem
You need a tree that can store a number of child nodes in each of its nodes. A binary tree would work if each node needs to have only two children, but, in this case, each node needs to have a fixed number of child nodes greater than two.
Solution
Use the following NTree class to create the root
node for the n-ary tree:
using System;
using System.Collections;
public class NTree
{
public NTree( )
{
maxChildren = int.MaxValue;
}
public NTree(int maxNumChildren)
{
maxChildren = maxNumChildren;
}
// The root node of the tree
protected NTreeNodeFactory.NTreeNode root = null;
// The maximum number of child nodes that a parent node may contain
protected int maxChildren = 0;
public void AddRoot(NTreeNodeFactory.NTreeNode node)
{
root = node;
}
public NTreeNodeFactory.NTreeNode GetRoot( )
{
return (root);
}
public int MaxChildren
{
get {return (maxChildren);}
}
}The methods defined in Table 10-6 are of particular
interest to using an NTree
object.
Table 10-6. Members of the NTree class
|
Member |
Description |
|---|---|
|
Overloaded constructor |
This constructor creates an NTree(int
where |
|
|
A read-only property to retrieve the maximum number of children any node may have. Its syntax is: int
The value this property returns is set in the constructor. |
|
|
Adds a node to the tree. Its syntax ... |