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("未找到节点");
//        }
    }
}
相关推荐
我是Superman丶3 小时前
Arduino IDE 安装教程:Windows/macOS/Linux 开发环境搭建
ide·windows·macos
辻弋2014 小时前
自动检测硬件生成驱动清单、实时监控FPS、120秒性能记录——30+项优化模块化开关,所有改动可精确复原
服务器·windows·游戏引擎·电脑·开源软件
江湖人称菠萝包4 小时前
【Windows】《深入浅出Windows API程序设计:编程基础篇》笔记-Chapter8-子窗口控件
windows·笔记
其实防守也摸鱼6 小时前
OpenClaw Windows 踩坑实战指南
运维·服务器·数据库·windows·github·copilot
佳&弥10 小时前
后渗透痕迹清理
服务器·windows·web安全·网络安全
MSTcheng.11 小时前
【Linux学习】Linux学习第四弹——Linux基本指令3
linux·windows·学习·操作系统·指令
霸道流氓气质12 小时前
MyBatis 与 SQL 层面关键技术详解
windows·sql·mybatis
一直走下去-明12 小时前
在 Windows 上安装 uv
windows·uv
Lost of 程序猿13 小时前
C# 12 / .NET 9 新特性机制深度:编译器替你写了什么,哪些糖吃下去会出事
windows·c#·.net
编程的一拳超人1 天前
DeepSeek Harness Linux/macOS/Windows 本地下载、启动与模型配置指南
linux·windows·macos·deepseek