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("未找到节点");
//        }
    }
}
相关推荐
天若有情6738 小时前
程序员原创|借鉴JS事件冒泡,根治电脑文件混乱的“冒泡整理法”
开发语言·javascript·windows·ecmascript·电脑·办公·日常
九成宫8 小时前
Outlook使用
windows·笔记·outlook·办公
盘古工具9 小时前
【分享】打开PDF文件的几种方式
windows·pdf
萧行之14 小时前
Ubuntu+Windows双系统:解决GRUB不显示Windows启动项、一闪而过问题
linux·windows·ubuntu
深念Y14 小时前
踩坑实录:把 Windows 默认 PowerShell 换成 7.x 到底有多坑?一条龙解决指南
windows·乱码·bug·控制台·powershell·管道·流式
夜猫逐梦14 小时前
[开发经验] DLL注入中控制台窗口无法关闭的排查与修复
c++·windows·控制台
无限进步_15 小时前
C++ 多态机制完全解析:从虚函数重写到动态绑定原理
java·c语言·jvm·数据结构·c++·windows·后端
天都35715 小时前
青少年ctf 日志排查 复盘
windows·网络安全·应急响应
南汁bbj18 小时前
彻底解决!Milvus远程连接报错code=2、gRPC超时问题(Windows访问Linux服务终极方案)
linux·windows·milvus
草履虫君21 小时前
windows系统装机,小白win10装机教程wepe模式,包括系统盘怎么制作,bios怎么设置
windows·经验分享