11.11
普通树
- 节点类定义
java
import java.util.ArrayList;
import java.util.List;
class GeneralNode {
String data;
List
public GeneralNode(String data) {
this.data = data;
this.children = new ArrayList<>();
}
// 添加子节点
public void addChild(GeneralNode child) {
this.children.add(child);
}
}
- 构建与遍历
java
public class GeneralTree {
// 深度优先遍历
public static void dfs(GeneralNode node, int depth) {
if (node == null) return;
// 缩进显示层级
System.out.println(" ".repeat(depth) + "- " + node.data);
for (GeneralNode child : node.children) {
dfs(child, depth + 1);
}
}
public static void main(String[] args) {
// 构建组织架构树
GeneralNode ceo = new GeneralNode("CEO");
GeneralNode techDir = new GeneralNode("技术总监");
ceo.addChild(techDir);
techDir.addChild(new GeneralNode("前端负责人"));
// 遍历测试
dfs(ceo, 0);
// 输出:
// - CEO
// - 技术总监
// - 前端负责人
}}

浙公网安备 33010602011771号