摘要: 树形结构在计算机科学中是一种常见的数据结构,在许多领域如文件系统、组织结构图、分类目录等都有广泛的应用。本文将重点探讨在 Java 中如何有效地循环遍历树形结构,包括使用递归和非递归的方法来实现对树形数据的操作。
一、引言
二、递归方式遍历树形结构
(一)基本原理
class TreeNode {
int value;
List<TreeNode> children;
public TreeNode(int value) {
this.value = value;
this.children = new ArrayList<>();
}
}
(二)前序遍历(Pre - order Traversal)示例
public class TreeTraversal {
public static void preOrderTraversal(TreeNode root) {
if (root!= null) {
System.out.println(root.value);
for (TreeNode child : root.children) {
preOrderTraversal(child);
}
}
}
}
(三)中序遍历(In - order Traversal)示例
(四)后序遍历(Post - order Traversal)示例
public static void postOrderTraversal(TreeNode root) {
if (root!= null) {
for (TreeNode child : root.children) {
postOrderTraversal(child);
}
System.out.println(root.value);
}
}
三、非递归方式遍历树形结构
(一)使用栈(Stack)实现
public static void iterativePreOrderTraversal(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode current = stack.pop();
System.out.println(current.value);
for (int i = current.children.size() - 1; i >= 0; i--) {
stack.push(current.children.get(i));
}
}
}
(二)使用队列(Queue)实现层次遍历
public static void levelOrderTraversal(TreeNode root) {
if (root == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
System.out.println(current.value);
for (TreeNode child : current.children) {
queue.add(child);
}
}
}