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("未找到节点");
//        }
    }
}
相关推荐
天地之于壹炁兮6 小时前
编程I/O入门指南:核心操作全解析
数据库·windows·microsoft
深圳市恒讯科技7 小时前
英国服务器Windows系统远程桌面安装与优化
运维·服务器·windows
像风一样的男人@8 小时前
python --两个文件夹文件名比对(yolo 图和label标注比对检查)
windows·python·yolo
diannao72011 小时前
实时将大模型的解决方案转换为随机应变的机器人指令
开发语言·windows·python·机器人
奔跑吧邓邓子12 小时前
【C语言实战(75)】C语言内存探秘:泄漏检测与分析实战
linux·c语言·windows·内存·开发实战·泄露检测
刘恒12345678921 小时前
Windows 10 docker 配置(PHP+Nginx+Mysql)(thinkphp5项目)环境
windows·docker·php
苏比的博客1 天前
Windows MFC添加类,变量,类导向
c++·windows·mfc
孫治AllenSun1 天前
【算法】图相关算法和递归
windows·python·算法
TeleostNaCl1 天前
解决 Chrome 无法访问网页但无痕模式下可以访问该网页 的问题
前端·网络·chrome·windows·经验分享
寒某1 天前
在Windows上部署RAGFlow
windows·ai