自学内容网 自学内容网

java实现树形递归

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TreeBuilder {

    // 定义树节点结构
    static class TreeNode {
        private int id;
        private int parentId;
        private String name;
        private List<TreeNode> children = new ArrayList<>();

        public TreeNode(int id, int parentId, String name) {
            this.id = id;
            this.parentId = parentId;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public int getParentId() {
            return parentId;
        }

        public String getName() {
            return name;
        }

        public List<TreeNode> getChildren() {
            return children;
        }

        public void addChild(TreeNode child) {
            this.children.add(child);
        }

        @Override
        public String toString() {
            return "TreeNode{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", children=" + children +
                    '}';
        }
    }

    /**
     * 构建树形结构
     * @param nodes 原始节点列表
     * @return 树的根节点列表
     */
    public static List<TreeNode> buildTree(List<TreeNode> nodes) {
        // 创建一个映射,用于快速查找节点
        Map<Integer, TreeNode> nodeMap = nodes.stream()
                .collect(Collectors.toMap(TreeNode::getId, node -> node));

        // 保存根节点列表
        List<TreeNode> rootNodes = new ArrayList<>();

        // 构建树形结构
        for (TreeNode node : nodes) {
            if (node.getParentId() == 0) {
                // 根节点
                rootNodes.add(node);
            } else {
                // 找到父节点并将当前节点添加为其子节点
                TreeNode parent = nodeMap.get(node.getParentId());
                if (parent != null) {
                    parent.addChild(node);
                }
            }
        }

        return rootNodes;
    }

    public static void main(String[] args) {
        // 模拟数据
        List<TreeNode> nodeList = new ArrayList<>();
        nodeList.add(new TreeNode(1, 0, "Root1"));
        nodeList.add(new TreeNode(2, 0, "Root2"));
        nodeList.add(new TreeNode(3, 1, "Child1.1"));
        nodeList.add(new TreeNode(4, 1, "Child1.2"));
        nodeList.add(new TreeNode(5, 3, "Child1.1.1"));
        nodeList.add(new TreeNode(6, 2, "Child2.1"));

        // 构建树
        List<TreeNode> tree = buildTree(nodeList);

        // 打印结果
        System.out.println(tree);
    }
}


原文地址:https://blog.csdn.net/qq_41228643/article/details/145183870

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!