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("未找到节点");
//        }
    }
}
相关推荐
吾心不朽18 分钟前
PowerPoint无法从所选的文件中插入视频,验证此媒体格式所必需的64位编码解码器是否已安装,然后重试
windows
爱宇阳1 小时前
Windows 通过 SSH 下载服务器目录并完整上传到指定服务器目录(scp / rsync 实战教程)
服务器·windows·ssh
五阿哥永琪2 小时前
Stream流式编程 练习题
windows
雪风飞舞2 小时前
conda 常用命令
linux·windows·conda
寺中人2 小时前
ms 17-010 永恒之蓝复现
windows·永恒之蓝
ChoSeitaku2 小时前
16.C++入门:list|手撕list|反向迭代器|与vector对比
c++·windows·list
酒醉的胡铁2 小时前
Docker Desktop 数据迁移完整流程(Windows 10/11 x64)
windows·docker·容器
YJlio3 小时前
Registry Usage (RU) 学习笔记(15.5):注册表内存占用体检与 Hive 体量分析
服务器·windows·笔记·python·学习·tcp/ip·django
星火开发设计4 小时前
Python数元组完全指南:从基础到实战
开发语言·windows·python·学习·知识·tuple
hudawei9964 小时前
win和Mac在创建python虚拟环境,启动环境等操作的异同
windows·python·macos·虚拟环境