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("未找到节点");
//        }
    }
}
相关推荐
洛阳泰山几秒前
Windows系统部署MongoDB数据库图文教程
数据库·windows·mongodb
阿斯顿法国红酒快37 分钟前
Windows系统安全加固
网络·windows·安全·网络安全·系统安全·ddos
C++ 老炮儿的技术栈2 小时前
自定义CString类与MFC CString类接口对比
c语言·c++·windows·qt·mfc
不讲废话的小白3 小时前
Windows系统永久暂停更新操作步骤
windows
正经教主5 小时前
【基础】Windows开发设置入门4:Windows、Python、Linux和Node.js包管理器的作用和区别(AI整理)
linux·windows·python·包管理器
明月与玄武5 小时前
Pywinauto:轻松实现Windows桌面自动化实战
windows·pywinauto·windows桌面自动化
渴望技术的猿6 小时前
Windows 本地部署MinerU详细教程
java·windows·python·mineru
Mast Sail1 天前
windows下authas调试tomcat
java·windows·tomcat·authas
疯狂的挖掘机1 天前
记一次从windows连接远程Linux系统来控制设备采集数据方法
linux·运维·windows
前进的程序员1 天前
C++ 在 Windows 和 Linux 平台上的开发差异及常见问题
linux·c++·windows