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("未找到节点");
//        }
    }
}
相关推荐
界面开发小八哥2 小时前
界面控件DevExpress WPF v25.1预览 - 支持Windows 11系统强调色
windows·wpf·界面控件·devexpress·ui开发·.net 9
岫珩5 小时前
“由于启动计算机时出现了页面文件配置问题,Windows在你的计算机上创建了一个临时页面文件。。。”的问题解决
windows
李菠菜6 小时前
解决Windows系统下Git克隆时报错“unable to checkout working tree”的方法详解
windows·git
子非衣10 小时前
Windows云主机远程连接提示“出现了内部错误”
服务器·windows
剁椒排骨11 小时前
win11什么都不动之后一段时间黑屏桌面无法显示,但鼠标仍可移动,得要熄屏之后才能进入的四种解决方法
运维·windows·经验分享·计算机外设·win11·win10
李菠菜11 小时前
Windows Terminal 集成 Git Bash 的简洁配置指南
windows·git
大数据魔法师12 小时前
Hadoop生态圈框架部署 - Windows上部署Hadoop
大数据·hadoop·windows
江沉晚呤时14 小时前
深入了解C# List集合及两种常见排序算法:插入排序与堆排序
windows·sql·算法·oracle·c#·排序算法·mybatis
聂 可 以20 小时前
推荐几个可以免费下载视频的软件(Neat Download Manager、蜗牛下载助手、bilidown)
windows·开源软件
菜鸟射手1 天前
QT creater和vs2017文件路径问题
linux·c++·windows·qt