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("未找到节点");
//        }
    }
}
相关推荐
Starmoon_dhw17 小时前
重塑你的Windows文件夹图标 Folder Theme Studio
windows
七牛云行业应用18 小时前
Codex Computer Use 完全指南:让 AI 接管你的桌面(含 Windows 版)
人工智能·windows
IMPYLH18 小时前
HTML 的 <dl> 元素
linux·windows·html
2501_936415691 天前
可变参数&综合练习&斗地主游戏
java·windows·游戏
西安景驰电子1 天前
PCIe 授时卡原理及应用
运维·服务器·windows·单片机·嵌入式硬件·fpga开发
wardenlzr2 天前
VSCode 运行 Live Server 提示「Windows 找不到文件 Chrome」问题全解析
chrome·windows·vscode
好好沉淀2 天前
Windows 下升级 Maven 3.6.1 到 3.9.9 踩坑全记录
java·windows·maven
weixin_436525072 天前
Windows 上终止占用的端口进程
windows
古道青阳2 天前
Duilib 技术全景剖析
c++·windows
jing.wang_20252 天前
NVIDIA CUDA C++编程环境搭建--Windows + Ubuntu 22.04
c++·windows·ubuntu·gpu算力