在 Java 開發中,樹結構是一種常見的數據結構,廣泛應用於文件系統、組織架構、XML/JSON 解析等場景。本文將通過一個完整的示例,展示如何使用 Java 實現一個支持動態節點增刪查、遞歸遍歷的通用樹結構,並提供可直接運行的代碼。
樹結構由節點組成,每個節點包含數據、父節點引用及子節點列表。樹類負責管理根節點,提供添加節點、查找節點、遍歷展示等核心操作。採用泛型設計,使樹能存儲任意類型的數據。
package com.app;
import java.util.ArrayList;
import java.util.List;
public class TreeNode<T> {
public T data;
private TreeNode<T> parent;
public List<TreeNode<T>> children;
public TreeNode(T data) {
this.data = data;
this.parent = null;
this.children = new ArrayList<>();
}
public TreeNode<T> getParent() {
return parent;
}
public void setParent(TreeNode<T> parent) {
this.parent = parent;
}
public List<TreeNode<T>> getChildren() {
return children;
}
}
package com.app;
public class Tree<T> {
public TreeNode<T> root;
public Tree() {}
/**
* 添加節點
* @param parent 父節點,為 null 時添加為根節點
* @param data 新節點數據
*/
public void addNode(TreeNode<T> parent, T data) {
if (parent == null) {
if (root == null) {
root = new TreeNode<>(data);
}
} else {
TreeNode<T> newNode = new TreeNode<>(data);
newNode.setParent(parent);
parent.getChildren().add(newNode);
}
}
/**
* 遞歸查找節點
*/
public TreeNode<T> search(TreeNode<T> current, T target) {
if (current == null) return null;
if (current.data.equals(target)) {
return current;
}
for (TreeNode<T> child : current.getChildren()) {
TreeNode<T> result = search(child, target);
if (result != null) return result;
}
return null;
}
public TreeNode<T> getNode(T data) {
return search(root, data);
}
/**
* 前序遍歷展示樹結構
*/
public void showTree(TreeNode<T> node) {
if (node != null) {
System.out.println(node.data);
for (TreeNode<T> child : node.getChildren()) {
showTree(child);
}
}
}
}
package com.app;
public class App {
public static void main(String[] args) {
Tree<String> tree = new Tree<>();
// 構建樹結構
tree.addNode(null, "string"); // 根節點
tree.addNode(tree.getNode("string"), "hello");
tree.addNode(tree.getNode("string"), "world");
tree.addNode(tree.getNode("hello"), "sinny");
tree.addNode(tree.getNode("hello"), "fredric");
tree.addNode(tree.getNode("world"), "Hi");
tree.addNode(tree.getNode("world"), "York");
// 遍歷輸出
System.out.println("樹結構遍歷結果:");
tree.showTree(tree.root);
System.out.println("end of the test");
}
}
樹結構遍歷結果:
string
hello
sinny
fredric
world
Hi
York
end of the test
本文展示了基於泛型的通用樹結構實現,代碼結構清晰、易於擴展。掌握樹結構的構建與遍歷是處理層級數據的基礎,可根據業務需求進一步豐富功能。