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 小时前
【vue3+tauri+rust】如何实现下载文件mac+windows
windows·macos·rust
李洋-蛟龙腾飞公司2 小时前
HarmonyOS NEXT应用元服务常见列表操作多类型列表项场景
windows
new_zhou6 小时前
Windows qt打包编译好的程序
开发语言·windows·qt·打包程序
Rocket MAN6 小时前
Rovo Dev CLI Windows 安装与使用指南
windows
fzyz12310 小时前
Windows系统下WSL从C盘迁移方案
人工智能·windows·深度学习·wsl
csdn_aspnet12 小时前
在 Windows 机器上安装和配置 RabbitMQ
windows·rabbitmq
csdn_aspnet13 小时前
Windows Server 上的 RabbitMQ 安装和配置
windows·rabbitmq
热爱生活的猴子17 小时前
Poetry 在 Linux 和 Windows 系统中的安装步骤
linux·运维·windows
R-sz20 小时前
java流式计算 获取全量树形数据,非懒加载树,递归找儿
java·开发语言·windows
柳鲲鹏1 天前
WINDOWS最快布署WEB服务器:apache2
服务器·前端·windows