How to traverse binary tree by breadth (Part II) ?

1 minute read

Here I will introduce the breadth first traversal of binary tree.

The principe is that you traverse the binary tree level by level.

This traversal is quite different than depth first traversal. In depth first traversal you can use recursive method to traverse.

Here is one solution using a queue.

/// <summary>
/// breadth-first traversal 宽度遍历树
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="node"></param>
public void Traversal<T>(Node<T> node)
    //create a Node<T> queue
    var treeQueue = new Queue<Node<T>>();
    //initialize queue with tree root node

    //if queue has elements
    while (treeQueue.Count > 0)
        //dequeue the queue's first node 
        Node<T> current = treeQueue.Dequeue();

        //print the node name
        //if node has Left leaf, enqueue it
        if (current.LNode != null)
        //if node has right leaf, enqueue it
        if (current.RNode != null)
SUN Jiangong

SUN Jiangong

A senior .NET engineer, software craftsman. Passionate about new technologies.