diff --git a/codes/java/chapter_graph/graph_bfs.java b/codes/java/chapter_graph/graph_bfs.java index ffcf6d0da..55304ebf1 100644 --- a/codes/java/chapter_graph/graph_bfs.java +++ b/codes/java/chapter_graph/graph_bfs.java @@ -16,9 +16,11 @@ public class graph_bfs { // 顶点遍历序列 List res = new ArrayList<>(); // 哈希表,用于记录已被访问过的顶点 - Set visited = new HashSet<>() {{ add(startVet); }}; + Set visited = new HashSet<>(); + visited.add(startVet); // 队列用于实现 BFS - Queue que = new LinkedList<>() {{ offer(startVet); }}; + Queue que = new LinkedList<>(); + que.offer(startVet); // 以顶点 vet 为起点,循环直至访问完所有顶点 while (!que.isEmpty()) { Vertex vet = que.poll(); // 队首顶点出队 diff --git a/codes/java/chapter_tree/binary_tree_bfs.java b/codes/java/chapter_tree/binary_tree_bfs.java index cdf57ac68..93fc33133 100644 --- a/codes/java/chapter_tree/binary_tree_bfs.java +++ b/codes/java/chapter_tree/binary_tree_bfs.java @@ -13,7 +13,8 @@ public class binary_tree_bfs { /* 层序遍历 */ static List levelOrder(TreeNode root) { // 初始化队列,加入根节点 - Queue queue = new LinkedList<>() {{ add(root); }}; + Queue queue = new LinkedList<>(); + queue.add(root); // 初始化一个列表,用于保存遍历序列 List list = new ArrayList<>(); while (!queue.isEmpty()) { diff --git a/codes/java/utils/TreeNode.java b/codes/java/utils/TreeNode.java index 954494ba9..13e116052 100644 --- a/codes/java/utils/TreeNode.java +++ b/codes/java/utils/TreeNode.java @@ -26,7 +26,8 @@ public class TreeNode { return null; TreeNode root = new TreeNode(list.get(0)); - Queue queue = new LinkedList<>() {{ add(root); }}; + Queue queue = new LinkedList<>(); + queue.add(root); int i = 0; while (!queue.isEmpty()) { TreeNode node = queue.poll(); @@ -51,7 +52,7 @@ public class TreeNode { List list = new ArrayList<>(); if (root == null) return list; - Queue queue = new LinkedList<>() {{ add(root); }}; + Queue queue = new LinkedList() {{ add(root); }}; while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node != null) {