package com.fr.plugin.event.manager.data; import java.util.LinkedList; import java.util.List; /** * @author Joe * Created by Joe on 12/14/2020 */ public class MyTree { /** * 树节点 */ private MyNode data; /** * 父节点,根没有父节点 */ private MyTree parent; /** * 子节点,叶子节点没有子节点 */ private List children; /** * 保存了当前节点及其所有子节点,方便查询 */ private List elementsIndex; private boolean visible; /** * 构造函数 * * @param data */ public MyTree(MyNode data) { this.data = data; this.children = new LinkedList<>(); this.elementsIndex = new LinkedList<>(); this.elementsIndex.add(this); this.visible = true; } public MyNode getData() { return data; } public void setVisible(boolean visible) { this.visible = visible; } public List getChildren() { return children; } public List getElementsIndex() { return elementsIndex; } /** * 判断是否为根:根没有父节点 * * @return */ public boolean isRoot() { return parent == null; } /** * 判断是否为叶子节点:子节点没有子节点 * * @return */ public boolean isLeaf() { return children.size() == 0; } /** * 添加一个子节点 * * @param child * @return */ public MyTree addChild(MyNode child) { MyTree childNode = new MyTree(child); childNode.parent = this; this.children.add(childNode); this.registerChildForSearch(childNode); return childNode; } public void removeChild(MyTree child) { // 如果是根的话,就保留 if (child.parent != null) { child.parent.children.remove(child); child.parent = null; } } /** * 递归为当前节点以及当前节点的所有父节点增加新的节点 * * @param node */ private void registerChildForSearch(MyTree node) { elementsIndex.add(node); if (parent != null) { parent.registerChildForSearch(node); } } public MyTree findChild(int index) { return children.get(index); } public int getChildrenSize() { return children.size(); } public int getIndexOfChild(Object child) { int count = getChildrenSize(); for (int i = 0; i < count; i++) { MyTree comp = findChild(i); if (comp == child) { return i; } } return -1; } }