动图理解:
广度优先遍历,即层次遍历,使用队列来实现。
通过每次获取队头数据,然后将队头出队,将队头的左孩子重新入队,队头的右孩子重新入队的思路实现广度优先遍历。
/**
* 节点定义
*/
public static class Tree {
Tree left;
Tree right;
int val;
public Tree(int val) {
this.val = val;
}
}
/**
* 广度优先遍历(BFS)
*/
public static void bfsTraversing(Tree root) {
// 1.判空
if (root == null) {
return;
}
// 2.定义队列
Queue<Tree> queue = new LinkedList<Tree>();
queue.add(root);
// 3.遍历队列
while (!queue.isEmpty()) {
// 4.获取队列的队头
Tree node = queue.peek();
// 5.移除队头
queue.remove();
// 6. 输出队头
System.out.print(node.val + " ");
// 7.如果左节点不为空,则加入到队列中
if (node.left != null) {
queue.add(node.left);
}
// 8.如果右节点不为空,则加入到节点中去
if (node.right != null) {
queue.add(node.right);
}
}
}