11.11

普通树

  1. 节点类定义

java
import java.util.ArrayList;
import java.util.List;

class GeneralNode {
String data;
List children; // 动态存储子节点

public GeneralNode(String data) {
    this.data = data;
    this.children = new ArrayList<>();
}

// 添加子节点
public void addChild(GeneralNode child) {
    this.children.add(child);
}

}

  1. 构建与遍历

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
    //   - 技术总监
    //     - 前端负责人

}}

posted @ 2025-11-11 21:07  喜欢写轻小说的日央  阅读(6)  评论(0)    收藏  举报