java 树型结构转list

复制代码
class TreeNode {
    int value;
    List<TreeNode> children;

    TreeNode(int value) {
        this.value = value;
        this.children = new ArrayList<>();
    }

    void addChild(TreeNode child) {
        children.add(child);
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public List<TreeNode> getChildren() {
        return children;
    }

    public void setChildren(List<TreeNode> children) {
        this.children = children;
    }
}
复制代码
public class TreeSearch {
    public static  List<TreeNode> treeToList(List<TreeNode> list) {
        List<TreeNode> result = new ArrayList<>();
        for(TreeNode test : list) {
            List<TreeNode> c = test.getChildren();
            result.add(test);
            if (c!=null) {
                result.addAll(treeToList(c));
                test.setChildren(null);
            }
        }
        return result;
    }


    public static TreeNode search(TreeNode root, int target) {

        if (root == null) {
            return null;
        }
        if (root.value == target) {
            return root;
        }
        for (TreeNode child : root.children) {
            TreeNode result = search(child, target);
            if (result != null) {
                return result;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        // 构建树结构
        TreeNode root = new TreeNode(1);
        root.addChild(new TreeNode(2));
        root.addChild(new TreeNode(3));
        root.children.get(0).addChild(new TreeNode(21));
        root.children.get(0).addChild(new TreeNode(22));
        root.children.get(1).addChild(new TreeNode(31));

        List<TreeNode> treeNodes = treeToList(root.children);
        for (TreeNode treeNode : treeNodes) {
            System.out.println(treeNode.value);
        }
        // 查找值为5的节点
//        TreeNode result = search(root, 2);
//        if (result != null) {
//            System.out.println("找到了节点: " + result.value);
//        } else {
//            System.out.println("未找到节点");
//        }
    }
}
相关推荐
Mr.亮先生17 小时前
# 把 DeepSeek 官方 Agent 工作台,直接装进 Windows 启动器里
windows·deepseek·harness
曹牧1 天前
C#:List<string>特定格式输出
windows·c#
易点云徐源1 天前
(已解决)Photoshop 多画板 Alt+拖动复制随机卡死 4~5 分钟
windows·photoshop
Dovis(誓平步青云)1 天前
DevEco Studio 6.1.1 Windows 安装实录:从下载校验到首次启动
android·开发语言·数据库·人工智能·windows·harmonyos
bosins1 天前
将 Hyper-V 上的 Ubuntu 虚拟机内容迁移到 WSL (Windows Subsystem for Linux) 中
linux·windows·ubuntu
ι:1 天前
DeepSeek Harness 桌面一键启动与网页背景修改指南
windows·学习·deepseekharness
zuozewei1 天前
7DGroup 开源 dsh-7d-tray-win 系统托盘插件
windows·代码复审
深念Y1 天前
Wine 运行 HiTool 踩坑记录
linux·windows·容器·桌面·wine·虚拟器
玖釉-1 天前
nvpro_core2 源码与架构解析:NVIDIA Vulkan 图形开发基础框架
c++·windows·图形渲染
淡海水1 天前
01-08-运行时-虚方法分派与接口调用的底层实现
linux·windows·microsoft·c#·虚方法·vtable·vsd