java 树形结构遍历
在Java中遍历树形结构可以使用深度优先算法(DFS)或广度优先算法(BFS)。
-
深度优先算法(DFS)的示例代码如下所示:
class TreeNode { int val; List<TreeNode> children; public TreeNode(int val) { this.val = val; this.children = new ArrayList<>(); } } public class Main { public static void main(String[] args) { // 创建一个树形结构 TreeNode root = new TreeNode(1); TreeNode child1 = new TreeNode(2); TreeNode child2 = new TreeNode(3); TreeNode child3 = new TreeNode(4); root.children.add(child1); root.children.add(child2); root.children.add(child3); // 调用递归函数进行深度优先遍历 dfsTraversal(root); } private static void dfsTraversal(TreeNode node) { if (node == null) return; System.out.println("当前节点值为:" + node.val); for (TreeNode child : node.children) { dfsTraversal(child); } } }
输出结果将按照根节点、子节点等顺序打印每个节点的值。
-
广度优先算法(BFS)的示例代码如下所示:
import java.util.*; class TreeNode { int val; List<TreeNode> children; public TreeNode(int val) { this.val = val; this.children = new ArrayList<>(); } } public class Main { public static void main(String[] args) { // 创建一个树形结构 TreeNode root = new TreeNode(1); TreeNode child1 = new TreeNode(2); TreeNode child2 = new TreeNode(3); TreeNode child3 = new TreeNode(4); root.children.add(child1); root.children.add(child2); root.children.add(child3); // 调用迭代函数进行广度优先遍历 bfsTraversal(root); } private static void bfsTraversal(TreeNode node) { Queue<TreeNode> queue = new LinkedList<>(); queue.offer(node); while (!queue.isEmpty()) { TreeNode current = queue.poll(); System.out.println("当前节点值为:" + current.val); for (TreeNode child : current.children) { queue.offer(child); } } } }
-