A frequently occurring interview question is to print the nodes of a tree using the breadth first traversal. The breadth first traversal of a tree involves visiting each node from left to right at each level on the tree starting from the root and descending to the leaves. The order in which each sibling occurs is the order in which their parents occur. Dijkstra's algorithm uses this to order the visits in the breadth first traversal by maintaining a queue. The root is added to the queue. There are no more nodes at this level. When the root is dequeued, its siblings if any are added to the queue. When one of the siblings is dequeue, its siblings are enqueued. When we dequeue the last node at any level and add its siblings to queue, the next node to be dequeued is the first node of the next level. We repeat this until the queue is empty. The queue is empty when all of the nodes have been added and removed. Since the visits are ordered the time complexity is linear.
static void PrintBreadthNodes(BinaryTreeNode root)
{
if (root == null) return;
var list = new List<BinaryTreeNode?>(){null};
list.Add(root);
while (list.Count > 0)
{
var item = list.First();
list.RemoveAt(0);
if (item != null)
{
Console.Write(item);
if (item.left != null) list.Add(item.left);
if (item.right != null) list.Add(item.right);
}
else
{
if (list.Count == 0) return;
list.Add(null);
Console.WriteLine();
}
}
}
static void PrintBreadthNodes(BinaryTreeNode root)
{
if (root == null) return;
var list = new List<BinaryTreeNode?>(){null};
list.Add(root);
while (list.Count > 0)
{
var item = list.First();
list.RemoveAt(0);
if (item != null)
{
Console.Write(item);
if (item.left != null) list.Add(item.left);
if (item.right != null) list.Add(item.right);
}
else
{
if (list.Count == 0) return;
list.Add(null);
Console.WriteLine();
}
}
}
No comments:
Post a Comment