class App
{
public App()
{
BinaryTree bt = new BinaryTree();
Node root = bt.AddChild(bt.Root, 1);
bt.AddChild(root, 2);
bt.AddChild(root, 3);
bt.AddChild(root, 4);
bt.AddChild(root, 5);
bt.AddChild(root, 6);
bt.AddChild(root, 7);
bt.LevelOrder(root);
}
}
class BinaryTree
{
public class Node
{
public int Data { get; private set; }
public Node Left;
public Node Right;
public Node(int data)
{
Data = data;
}
}
public Node Root { get; private set; }
public void LevelOrder(Node root)
{
if (root == null) return;
Queue<Node> nodes = new Queue<Node>();
nodes.Enqueue(root);
while (true)
{
root = nodes.Dequeue();
Console.WriteLine(root.Data);
if (root.Left != null)
{
nodes.Enqueue(root.Left);
if (root.Left.Right != null) nodes.Enqueue(root.Left.Right);
}
if (nodes.Count == 0) return;
}
}
public Node AddChild(Node root, int data)
{
if (root == null)
{
Console.WriteLine("root node: {0}", data);
return new Node(data);
}
else
{
return AddChildRecursive(root, data);
}
}
public Node AddChildRecursive(Node root, int data)
{
if (root.Left == null)
{
Console.WriteLine("Parent Node: {0}, AddChild Left Node: {1}", root.Data, data);
return root.Left = new Node(data);
}
else if (root.Left.Right == null)
{
Console.WriteLine("{0} Sibling Node: {1}", root.Left.Data, data);
return root.Left.Right = new Node(data);
}
else
{
if (root.Left.Left == null || root.Left.Left.Right == null)
{
return AddChildRecursive(root.Left, data);
}
else if (root.Left.Right.Left == null || root.Left.Right.Left.Right == null)
{
return AddChildRecursive(root.Left.Right, data);
}
else
{
throw new InvalidOperationException();
}
}
}
}