循环遍历树形结构通常有两种方法:递归和迭代。下面是两种方法的示例代码:
1. 递归遍历
假设有一个树节点类 TreeNode
:
import java.util.ArrayList;
import java.util.List;
class TreeNode {
int value;
List<TreeNode> children;
TreeNode(int value) {
this.value = value;
this.children = new ArrayList<>();
}
void addChild(TreeNode child) {
this.children.add(child);
}
}
递归遍历树:
public class TreeTraversal {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode child1 = new TreeNode(2);
TreeNode child2 = new TreeNode(3);
root.addChild(child1);
root.addChild(child2);
child1.addChild(new TreeNode(4));
child1.addChild(new TreeNode(5));
child2.addChild(new TreeNode(6));
traverseTree(root);
}
static void traverseTree(TreeNode node) {
if (node == null) return;
System.out.println(node.value);
for (TreeNode child : node.children) {
traverseTree(child);
}
}
}
2. 迭代遍历
使用栈进行迭代遍历:
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class TreeTraversal {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode child1 = new TreeNode(2);
TreeNode child2 = new TreeNode(3);
root.addChild(child1);
root.addChild(child2);
child1.addChild(new TreeNode(4));
child1.addChild(new TreeNode(5));
child2.addChild(new TreeNode(6));
traverseTreeIteratively(root);
}
static void traverseTreeIteratively(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
System.out.println(node.value);
// Add children to stack (reverse order to maintain correct traversal order)
for (int i = node.children.size() - 1; i >= 0; i--) {
stack.push(node.children.get(i));
}
}
}
}
这两种方法可以根据需要选择使用。递归方法直观易懂,而迭代方法适用于深度较大的树,避免了栈溢出的问题。