# Hierarchical traversal of binary trees

#### Preface

For binary trees, hierarchical traversal is very common, but it is very important because it is widely used, for example, to find the height and width of binary trees. It is necessary for any programmer to master.

#### thinking

Very simple, using queues to traverse. At the beginning, if the root node is not empty, it will be queued. If the queue is not empty, it will cycle, queue an element and visit it. If the left child is not empty, its left child will be queued. If the right child is not empty, put the right child in the team. This continues until the queue is empty and the traversal ends.

#### Codes

``````/**
* Define binary tree structure
* @author Fairy2016
*
*/
class BiTree {
int data;
BiTree lchild;
BiTree rchild;
}
/**
* Define queue structure
* @author Fairy2016
*
*/
class Queue {
BiTree data[];
int front;
int rear;
}
/**
* Binary tree level traversal algorithm
* @author Fairy2016
*
*/
public class LayerThrough {
//According to the given sequence, a complete binary tree is established
public static BiTree CreateCompleteBiTree(int a[], int n) {
BiTree nodes[] = new BiTree[n];
//Initialize each node
for(int i = 0; i < n; i++) {
nodes[i] = new BiTree();
nodes[i].data = a[i];
nodes[i].lchild = nodes[i].rchild = null;
}
//Connect all nodes according to the relation of complete binary tree (in fact, odd left even right)
for(int i = 1; i <= n/2; i++) {
nodes[i-1].lchild = nodes[2*i-1];
if(2*i < n) {
nodes[i-1].rchild = nodes[2*i];
}
}
return nodes[0];
}
//level traversal
public static void LayerOrder(BiTree T) {
if(T == null) {
return;
}
//Queue initialization
Queue Q = new Queue();
Q.front = Q.rear = -1;
Q.data = new BiTree[100];
Q.data[++Q.rear] = T;//Root join the team
while(Q.rear != Q.front) {
BiTree p = Q.data[++Q.front];//Team out
System.out.print(p.data+" ");//Visit
if(p.lchild != null) {
Q.data[++Q.rear] = p.lchild;//Left child joins the team
}
if(p.rchild != null) {
Q.data[++Q.rear] = p.rchild;//Right kid in line
}
}
}
public static void main(String args[]) {
int a[] = {1,2,3,4,5,6,7,8};
int n = 8;
BiTree T = CreateCompleteBiTree(a, n);
LayerOrder(T);
}
}

``````

Posted by nemonoman on Mon, 04 May 2020 16:29:57 -0700