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("未找到节点");
//        }
    }
}
相关推荐
John_ToDebug1 小时前
浏览器内核崩溃深度分析:从 MiniDump 堆栈到 BindOnce UAF 机制(未完待续...)
c++·chrome·windows
一位赵3 小时前
小练2 选择题
linux·运维·windows
学***54233 小时前
12款分区恢复软件: 恢复已删除/丢失的分区
windows
爱内卷的学霸一枚5 小时前
现代微服务架构实践:从设计到部署的深度解析
windows·微服务·架构
程序猿阿伟7 小时前
《Apple Silicon与Windows on ARM:引擎原生构建与模拟层底层运作深度解析》
arm开发·windows
软件资深者7 小时前
游戏组件DirectX修复工具(DirectX Repair)v4.4增强版
windows·游戏·电脑·系统修复
By北阳7 小时前
Windows 系统中 存储信息加载异常的表现,所有数值都显示为 “0000000” 乱码
windows
wukangjupingbb9 小时前
在 Windows 系统上一键部署 **Moltbot**
人工智能·windows·agent
x***r1519 小时前
maxima-5.47.0-win64数学计算软件安装步骤详解(附数学计算与绘图入门)
windows
汪碧康9 小时前
OpenClaw 原版和汉化版windows 和Linux 下的部署实践
linux·人工智能·windows·agent·clawdbot·moltbot·openclaw