I am in the process of learning data structures and I am trying to implement Binary Tree using Queue in C#.
Below are my Tree implementation classes.
public class Tree
{
public char Data { get; set; }
public Tree LChild { get; set; }
public Tree RChild { get; set; }
}
public class TreeImplementation
{
//Initialize tree nodes with data.
Tree _rootNodeF = new Tree {Data = 'F'};
Tree _lChildNodeD = new Tree { Data = 'D' };
Tree _rChildNodeJ = new Tree { Data = 'J' };
Tree _lChildNodeB = new Tree { Data = 'B' };
Tree _rChildNodeE = new Tree { Data = 'E' };
//Initialize an empty queue to use for tree traversal.
Queue<Tree> _treeQueue = new Queue<Tree>();
public TreeImplementation()
{
_rootNodeF.LChild = _lChildNodeD;
_rootNodeF.RChild = _rChildNodeJ;
_lChildNodeD.LChild = _lChildNodeB;
_lChildNodeD.RChild = _rChildNodeE;
}
public void LevelOrder()
{
//Add root node to the queue.
_treeQueue.Enqueue(_rootNodeF);
//Create tempNode to add next node to the queue.
Tree tempNode = new Tree();
while (_treeQueue.Count != 0)
{
tempNode = _treeQueue.Dequeue();
VisitedTreeNode(tempNode.Data);
if (tempNode.LChild == null) continue;
_treeQueue.Enqueue(tempNode.LChild);
if (tempNode.RChild != null)
{
_treeQueue.Enqueue(tempNode.RChild);
}
}
}
//Access the data at the node.
public void VisitedTreeNode(char queueData)
{
Console.WriteLine(queueData);
}
}
I am calling the LevelOrder() method in the main method in another class.
How can I improve my code?