CSharp Algorithm - How to traverse binary tree by breadth (Part II)
Posted on 2013-08-03 22:43 冰天雪域 阅读(242) 评论(0) 编辑 收藏 举报/*
Author: Jiangong SUN
*/
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 treeQueue.Enqueue(node); //if queue has elements while (treeQueue.Count > 0) { //dequeue the queue's first node Node<T> current = treeQueue.Dequeue(); //print the node name PrintNodeName(current); //if node has Left leaf, enqueue it if (current.LNode != null) treeQueue.Enqueue(current.LNode); //if node has right leaf, enqueue it if (current.RNode != null) treeQueue.Enqueue(current.RNode); } }
references;
http://www.cs.bu.edu/teaching/c/tree/breadth-first/
http://hectorea.com/blog/programming-interview-31-binarytree-traversal-by-levels-breadth-first/#