protected GPTreeNode GetTree()
{
// function node queue. the queue contains function node,
// which requires children. when a function node receives
// all children, it will be removed from the queue
Queue<GPTreeNode> functionNodes = new Queue<GPTreeNode>();
// create root node
GPTreeNode root = new GPTreeNode(genes[0]);
// check children amount of the root node
if (root.Gene.ArgumentsCount != 0)
{
root.Children = new List<GPTreeNode>();
// place the root to the queue
functionNodes.Enqueue(root);
// go through genes
for (int i = 1; i < length; i++)
{
// create new node
GPTreeNode node = new GPTreeNode(genes[i]);
// if next gene represents function, place it to the queue
if (genes[i].GeneType == GPGeneType.Function)
{
node.Children = new List<GPTreeNode>();
functionNodes.Enqueue(node);
}
// get function node from the top of the queue
GPTreeNode parent = (GPTreeNode)functionNodes.Peek();
// add new node to children of the parent node
parent.Children.Add(node);
// remove the parent node from the queue, if it is
// already complete
if (parent.Children.Count == parent.Gene.ArgumentsCount)
{
functionNodes.Dequeue();
// check the queue if it is empty
if (functionNodes.Count == 0)
break;
}
}
}
// return formed tree
return root;
}