递归生成树形结构
转载:https://www.cnblogs.com/newlangwen/p/9969904.html
节点树树形结构
Tree 结构
import java.util.List; /** * @Author fanwei * @date 2018-6-13 17:04 */ public class TreeNode { private Integer key; private String title; private Integer parentId; private List<TreeNode> children; public Integer getKey() { return key; } public String getTitle() { return title; } public Integer getParentId() { return parentId; } public void setParentId(Integer parentId) { this.parentId = parentId; } public void setTitle(String title) { this.title = title; } public void setKey(Integer key) { this.key = key; } public List<TreeNode> getChildren() { return children; } public void setChildren(List<TreeNode> children) { this.children = children; } }
Tree递归
5个方法实现递归树形结构
逻辑: 构建树形结构 —— 获取树形根菜单 —— 根据树形根菜单获取子菜单(递归调用)
/** * 递归封装树形菜单 * @Author fanwei * @date 2018-6-22 11:49 */ public class Tree { List<TreeNode> nodes = new ArrayList<TreeNode>(); public Tree(List<TreeNode> nodes) { super(); this.nodes = nodes; } /** * 构建树形结构 * * @return */ public List<TreeNode> buildTree() { List<TreeNode> treeNodes = new ArrayList<TreeNode>(); List<TreeNode> rootNodes = getRootNodes(); for (TreeNode rootNode : rootNodes) { buildChildNodes(rootNode); treeNodes.add(rootNode); } return treeNodes; } /** * 递归子节点 * * @param node */ public void buildChildNodes(TreeNode node) { List<TreeNode> children = getChildNodes(node); if (!children.isEmpty()) { for (TreeNode child : children) { buildChildNodes(child); } node.setChildren(children); } } /** * 获取父节点下所有的子节点 * * @param nodes * @param pnode * @return */ public List<TreeNode> getChildNodes(TreeNode pnode) { List<TreeNode> childNodes = new ArrayList<TreeNode>(); for (TreeNode n : nodes) { if (pnode.getKey().equals(n.getParentId())) { childNodes.add(n); } } return childNodes; } /** * 判断是否为根节点 * * @param nodes * @param inNode * @return */ public boolean rootNode(TreeNode node) { boolean isRootNode = true; for (TreeNode n : nodes) { if (node.getParentId().equals(n.getKey())) { isRootNode = false; break; } } return isRootNode; } /** * 获取集合中所有的根节点 * * @param nodes * @return */ public List<TreeNode> getRootNodes() { List<TreeNode> rootNodes = new ArrayList<TreeNode>(); for (TreeNode n : nodes) { if (rootNode(n)) { rootNodes.add(n); } } return rootNodes; } }