Traverse Binary Tree: Breadth First

Problem: Traverse a given binary tree, breadth first.

Solution 1: Iterate via a Queue

public class Node<T>
{
  public T Val;
  public Node<T> Left;
  public Node<T> Right;
}

public void BreadthTraversal(Node  n)
{
  Queue q = new Queue<Node>();
  q.Enqueue(n);

  while (q.Any())
  {
    var current = q.Dequeue();
    if (current.Left != null) q.Enqueue(current.Left);
    if (current.Right != null) q.Enqueue(current.Right);

    Console.WriteLine(current.Val);
  }
}

Leave a comment

Design a site like this with WordPress.com
Get started