一、二叉树的层次遍历
不同于二叉树先序遍历,中序遍历,后序遍历所用到的深度优先(DFS)思想,二叉树的层次遍历所用到的是广度优先(BFS)的思想,需要用到队列去实现。
基本步骤:
(1)先判断根节点非空,将根节点放入队列中。
(2)循环判断队列非空,从队列中取出节点并打印该节点的值。
(3)判断该节点的左右节点是否为空,不为空的话将其放入队列中。
(4)重复以上步骤,直到队列为空结束。
package tree;
public class Node { //节点类
//节点的权
int data;
//左节点
Node left;
//右节点
Node right;
//构造方法
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
**********************************
//层次遍历二叉树
public void layerTranverse() {
if(this.root == null) {
return;
}
Queue<Node> q = new LinkedList<Node>(); //创建一个队列
q.add(this.root); //将不为空的节点放到队列中
while(!q.isEmpty()) {
Node currentNode = q.poll(); //从队列中取出节点并打印其值
System.out.print(currentNode.data+" ");
if(currentNode.left != null) { //判断该节点左右节点不为空,放入队列
q.add(currentNode.left);
}
if(currentNode.right != null) {
q.add(currentNode.right);
}
}
}
- 运行截图: