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("未找到节点");
//        }
    }
}
相关推荐
大明者省1 小时前
Label Studio安装与启动
windows
武藤一雄1 小时前
C# 异常(Exception)处理避坑指南
windows·microsoft·c#·.net·.netcore·鲁棒性
soragui2 小时前
【Python】第 4 章:Python 数据结构实现
数据结构·windows·python
橘子编程4 小时前
操作系统原理:从入门到精通全解析
java·linux·开发语言·windows·计算机网络·面试
程序员大辉6 小时前
Win11精简版的天花板:Windows X-Lite 26H1 V3完整安装教程,老电脑也能装
windows·电脑
熊明才6 小时前
PM2 服务器服务运维入门指南
运维·服务器·windows
沉迷学习 日益消瘦6 小时前
(windows环境)白嫖阿里云百炼免费 Token 使用 Claude 教程
windows·阿里云·claude·token·百炼
Mr_Xuhhh7 小时前
深入浅出ArrayList:从线性表到洗牌算法,掌握Java集合核心
windows
sunfdf7 小时前
使用免费工具在 Windows 11/10/8/7 中扩展 C 盘的 3 种方法
windows
月走乂山8 小时前
Trae CLI 全局配置 - Windows PATH 配置
windows