package com.leromro.core.utils;



import java.util.List;

/**
 *  树工具
 */
public class ForestNodeMerger {
    public static <T extends INode<T>> List<T> merge(List<T> items) {
        ForestNodeManager<T> forestNodeManager = new ForestNodeManager(items);
        items.forEach((forestNode) -> {
            if (forestNode.getParentId() != null && forestNode.getParentId() != 0L) {
                INode<T> node = forestNodeManager.getTreeNodeAt(forestNode.getParentId());
                if (node != null) {
                    node.getChildren().add(forestNode);
                } else {
                    forestNodeManager.addParentId(forestNode.getId());
                }
            }

        });
        return forestNodeManager.getRoot();
    }

    public static <T extends INode<T>> void getTreeList(T tree, List<T> nodes) {
        if (tree == null) {
            return;
        }

        nodes.add(tree);

        List<T> childrens = tree.getChildren();
        if (childrens != null) {
            for (T child : childrens) {
                getTreeList(child, nodes);
            }
        }
    }


}
