
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Creating an n-ary Tree
|
651
public NTreeNode<U> BreadthFirstSearch(U targetObj)
{
Queue<NTreeNode<U>> row = new Queue<NTreeNode<U>>( );
row.Enqueue(this);
while (row.Count > 0)
{
// Get next node in queue.
NTreeNode<U> currentNode = row.Dequeue( );
// Is this the node we are looking for?
if (targetObj.CompareTo(currentNode.nodeValue) == 0)
{
return (currentNode);
}
for (int index = 0;
index < currentNode.CountImmediateChildren;
index++)
{
if (currentNode.Children[index] != null)
{
row.Enqueue(currentNode.Children[index]);
}
}
}
return (null);
}
public void PrintDepthFirst( )
{
Console.WriteLine("this: " + nodeValue.ToString( ));
for (int index = 0; index < childNodes.Length; index++)
{
if (childNodes[index] != null)
{
Console.WriteLine("\tchildNodes[" + index + "]: " +
childNodes[index].nodeValue.ToString( ));
}
else
{
Console.WriteLine("\tchildNodes[" + index + "]: NULL");
}
}
for (int index = 0; index < childNodes.Length; index++)
{
if (childNodes[index] != null)
{
childNodes[index].PrintDepthFirst( );
Example 11-15. Using the class to create the nodes for an n-ary tree (continued)