2023-01-06 03:39:19 +08:00
|
|
|
/**
|
2022-11-25 02:04:38 +08:00
|
|
|
* File: binary_tree_bfs.java
|
|
|
|
* Created Time: 2022-11-25
|
|
|
|
* Author: Krahets (krahets@163.com)
|
|
|
|
*/
|
|
|
|
|
2022-11-12 22:48:46 +08:00
|
|
|
package chapter_tree;
|
|
|
|
|
|
|
|
import include.*;
|
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
public class binary_tree_bfs {
|
|
|
|
/* 层序遍历 */
|
2023-02-15 03:36:22 +08:00
|
|
|
static List<Integer> levelOrder(TreeNode root) {
|
2023-04-09 04:32:17 +08:00
|
|
|
// 初始化队列,加入根节点
|
2022-11-12 22:48:46 +08:00
|
|
|
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
|
|
|
|
// 初始化一个列表,用于保存遍历序列
|
|
|
|
List<Integer> list = new ArrayList<>();
|
|
|
|
while (!queue.isEmpty()) {
|
|
|
|
TreeNode node = queue.poll(); // 队列出队
|
2023-04-09 04:32:17 +08:00
|
|
|
list.add(node.val); // 保存节点值
|
2022-11-12 22:48:46 +08:00
|
|
|
if (node.left != null)
|
2023-04-09 04:32:17 +08:00
|
|
|
queue.offer(node.left); // 左子节点入队
|
2022-11-12 22:48:46 +08:00
|
|
|
if (node.right != null)
|
2023-04-09 04:32:17 +08:00
|
|
|
queue.offer(node.right); // 右子节点入队
|
2022-11-12 22:48:46 +08:00
|
|
|
}
|
|
|
|
return list;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
/* 初始化二叉树 */
|
|
|
|
// 这里借助了一个从数组直接生成二叉树的函数
|
2023-01-08 22:18:23 +08:00
|
|
|
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
|
2022-11-12 22:48:46 +08:00
|
|
|
System.out.println("\n初始化二叉树\n");
|
|
|
|
PrintUtil.printTree(root);
|
|
|
|
|
|
|
|
/* 层序遍历 */
|
2023-02-15 03:36:22 +08:00
|
|
|
List<Integer> list = levelOrder(root);
|
2023-04-09 04:32:17 +08:00
|
|
|
System.out.println("\n层序遍历的节点打印序列 = " + list);
|
2022-11-12 22:48:46 +08:00
|
|
|
}
|
|
|
|
}
|