Print Binary Tree by layer -- print one layer per line
I. Problem Introduction
Given a binary tree, print the binary tree in the order of sequential traversal. However, each row needs to print a layer of data.
Ii. Algorithm Analysis
It is achieved through binary tree sequence traversal. However, two additional variables are required. One variable is used to save the number of nodes that have not been printed on the current layer, and the other variable stores the number of nodes to be printed on the next layer.
Binary Tree sequence traversal references: http://www.cnblogs.com/hapjin/p/5409921.html
Sequence printing reference:
Public void printTree (BinaryNode <T> root ){
If (root = null)
Return;
Queue <BinaryNode <T> queue = new Queue list <> ();
Int current; // number of nodes that have not been printed on the current Layer
Int next; // number of nodes in the next layer
Queue. offer (root );
Current = 1;
Next = 0;
While (! Queue. isEmpty ()){
BinaryNode <T> currentNode = queue. poll ();
System. out. printf ("%-4d", currentNode. element );
Current --;
If (currentNode. left! = Null ){
Queue. offer (currentNode. left );
Next ++;
}
If (currentNode. right! = Null ){
Queue. offer (currentNode. right );
Next ++;
}
If (current = 0 ){
System. out. println ();
Current = next;
Next = 0;
}
}
}