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("未找到节点");
//        }
    }
}
相关推荐
江湖人称菠萝包4 分钟前
【Windows】《深入浅出Windows API程序设计:核心编程篇》笔记-Chapter5-剪贴板
windows·笔记
小此方2 小时前
告别云服务器连接困扰——Windows下利用VirtualBox安装配置Ubuntu虚拟机详细教程
服务器·windows·ubuntu
TomEval19 小时前
【接口自动化】13 - 接口数据驱动与报告
运维·windows·自动化
Lydia 不加班20 小时前
Windows 服务器 人大金仓 54321 端口放行完整步骤
运维·服务器·windows
运维全栈笔记20 小时前
Windows 本地部署 Codex 全攻略:CC Switch 接入 DeepSeek 与模型自由切换
windows·深度学习·机器学习·chatgpt
C++ 老炮儿的技术栈1 天前
西门子 S7 常用存储区(I/Q/M/T/C/DB/PI/PQ)
linux·开发语言·c++·windows·qt·io
今天AI了吗1 天前
去中心化 AI 反馈系统:数据不上链,凭证与激励分开管
人工智能·windows·python·数据分析·去中心化·区块链·embedding
MOONICK1 天前
MFC 嵌入WPF控件
windows
web守墓人1 天前
【goed/ui】go开发windows原生应用之Helloworld篇
windows·ui·golang
Lysander.Jovian1 天前
安装Windows server 2016
windows