Binary tree width (breadth) first traversal
Java code is as follows:
import java.util.LinkedList;
import java.util.Queue;
public class Test1 {
private static class BTNode{
public int Data;
public BTNode Left;
public BTNode Right;
public BTNode(int data) {
Data=data;
Left=null;
Right=null;
}
public static BTNode CreateBinaryTree() {
BTNode root=new BTNode(1);
root.Left=new BTNode(2);
root.Right=new BTNode(3);
BTNode p=root.Left;
p.Left=new BTNode(4);
p.Right=new BTNode(5);
p=root.Right;
p.Right=new BTNode(6);
return root;
}
public static void ShowBinaryTree(BTNode root) {
if(root==null) {
System.out.println("This Binary tree is empty!");
return;
}
int sum=0;//The total nodes
Queue<BTNode> q=new LinkedList<BTNode>();
q.add(root);
int next=0;//Next level's nodes
int count=1;//This level's nodes
while(!q.isEmpty()) {
if(count==0) {//This level's nodes has been printed
count=next;
next=0;//reset next nodes
}
BTNode p=q.poll();
count--;
sum++;
System.out.print(p.Data);
if(p.Left!=null) {
q.add(p.Left);
next++;
}
if(p.Right!=null) {
q.add(p.Right);
next++;
}
if(count==0)System.out.println();
else System.out.print(" ");
}
System.out.println(sum);
}
}
public static void main(String[] args) {
BTNode Root=BTNode.CreateBinaryTree();
BTNode.ShowBinaryTree(Root);
}
}
Results are as follows: